How to learn react logo

These tutorials will give you a deeper understanding of React.js. Learn with examples from the Javascript UI library, covering the basics and the advanced.

Browse by tag:

Using props to dynamically pass data to a component

Props
  1. Define a basic button and declare a className of props.buttonStyles
  2. Pass the <Basicbutton /> into the App
  3. Use defaultProps to declare the className of props.buttonStyles as teal
  4. Wrap props.buttonStyles with backticks and add basic styling to the button with a second class in a string
  5. Copy and paste more buttons into the App component
  6. Change the buttonStyles prop to red and create a new class in between the style tags
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Changing button colours with Reusability</title>

    <style>
    // Inline styles go here

    // Step 2b
    .teal {
        background: teal;
    }

    // Step 6b
    .red {
        background: red;
    }

    // Step 4b
    .basicButtonStyles {
        height: 40px;
        width: 150px;
        color: white;
        font-size: 18px;
    }

    </style>

</head>

<body>
    <div id="root"></div>

    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script crossorigin src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>

    <script type="text/babel">

        // Step 1                                       Step 4a
        const BasicButton = props => <button className={`basicButtonStyles ${props.buttonStyles}`}>Click me!</button>
        // Step 2a
        BasicButton.defaultProps = {
            buttonStyles: 'teal',
        }

        const App = () => {

            return
                <div>
                    <h2>Click on a button</h2>
                    // Step 2
                    <BasicButton />
                    // Step 5
                    <BasicButton buttonStyles={red} />
                    <BasicButton />
                    // Step 6a
                    <BasicButton buttonStyles={red} />
                    <BasicButton />
                </div>
        }

        ReactDom.render(<App />, document.getElementById('root'));
    </script>

</body>

</html>

Challenge

Create dynamic text on some of the buttons with props.buttonText

How To Learn React is designed and developed by me, Blake Fletcher. It is a project intended to share the things I learn while working with the UI library. As I build things, complete tutorials, read blog posts, and watch videos, I'll add to the site. I hope to eventually bring on other contributors. If interested, send me an email at blkfltchr@gmail.com.