DEV Community

Collins Mutai
Collins Mutai

Posted on

Passing Props in React

Components & Props

Props are inputs which are passed into Components and return React elements describing what should appear on the screen. Components helps with re-usability, by splitting the UI into independent sections.

With this in mind let's use a simple app that returns a div element with an h1 that displays a title and a p tag that displays the content.

const App = () => {
        return (
            <div>
                <h1>Changes in Service</h1>
                <p>We just updated our privacy policy here to better service our customers.</p>
            </div>
        );
    }

    // Renders the App component into a div with id 'root'
    ReactDOM.render(<App />, document.querySelector('#root'));
</script>


<!--The App component above will be rendered into this-->
<div id="root"></div>
Enter fullscreen mode Exit fullscreen mode

Passing a Prop to a Component

Next we'll define a function component called Message which accepts a single "props"(properties). The Message component will be used to extract the h1 and p as a separate reusable entity in our app.

const Message = (props) => {
        return (
            <div>
                <h1>{props.title}</h1>
                <p>{props.content}</p>
            </div>
        );
    }

 // Renders the App component into a div with id 'root'
    ReactDOM.render(<App />, document.querySelector('#root'));
</script>


<!--The App component above will be rendered into this-->
<div id="root"></div>
Enter fullscreen mode Exit fullscreen mode

Rendering a Component

Now we can swap out the hard coded h1 title and p content by calling our Message component inside our app.

const App = () => {
        return (
            <div>
                <Message title="Changes in Service" content="We just updated our privacy policy here to better service our customers." />
            </div>
        );
    }

    const Message = (props) => {
        return (
            <div>
                <h1>{props.title}</h1>
                <p>{props.content}</p>
            </div>
        );
    }


    // Renders the App component into a div with id 'root'
    ReactDOM.render(<App />, document.querySelector('#root'));
</script>


<!--The App component above will be rendered into this-->
<div id="root"></div>
Enter fullscreen mode Exit fullscreen mode

The h1 and p is being passed as a single object which we refer to it as props.

That's all for today, thank you guys for following along till the end. For more detail explanation, please checkout React Docs, link attached below. Happy coding. 😎
Reference [https://reactjs.org/docs/components-and-props.html]

Top comments (0)