ReactJS - Passing values from one component to other components using props

If there is components hierarchy in which top level component is rendering child component, sometimes we would need to pass the value from parent component to child component. This can be done using props which is already available variable in component.

In each component, there is props object which holds data/properties passed to this component object at the time of creation. After component gets created, this associated property object props of that component could not be updated. So, props is read-only object in component. 

Now, if this is read-only object, where the values inside of this props will come from?

this Answer is this - When a component is composed or added or used, there you can specify these value with name. Its done exactly same as you specify attributes in html tags. So, attribute name become name of property in props and you can use the value hold by this name using this.props.propertyname.

 

Here is the example.

<!DOCTYPE html>
<html lang="en">

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

<head>
    <meta charset="UTF-8">
    <title>React Demo</title>
</head>
<body>
<script type="text/babel">



    class Message extends React.Component {
     render(){
            return <h1 style={{color:this.props.textColor}}>Hello {this.props.name}</h1>
        }
    }

    class MessageBox extends React.Component{
        render(){
            return <div style={{backgroundColor:'#18799f',padding:'20px'}}>
                <Message name="John" textColor={this.props.messageColor}/>
            </div>
        }
    }

    class Container extends React.Component{
        render(){
            return <div>
                <MessageBox messageColor="#ffffff"/>
            </div>
        }
    }

    ReactDOM.render(
        <Container/>,
        document.body
    );
</script>
</body>
</html>

Here Container component compose of MessageBox component and MessageBox component includes Message Component. Now, we want that Container component should be able to set the message color in the Message component. Here, In the Container component, colour #ffffff is being passed as attribute to MessageBox component with attribute name messageColor. In MessageBox component, you would receive this value in this.props.messageColor variable. Here, messageColor is the property of this component which can be accessed by props object. From MessageBox component, the value of this.props.messageColor is being passed to Message component with attribute name textColor. Again, inside Message component, this value would be available in textColor property in props object.

passing-values-from-parent-to-child

 

Tags