How to pass data from Parent component to Child component in React
Today we will show you how to pass data from parent component to child component in React JS using example.
Communication is the most important part of the single page application. So for that we will use props to communicate between two components (Passing data from parent to child component).
Passing Data Between React Components, React | pass data from parent to child component, Passing data from Parent to Child Components, How to pass props to components in React, Parent-Child Component Communication, how to pass value from one component to another component in reactjs.
Let’s take a simple example where we will have parent component which contains the normal input element and then pass the input value into the child component on change event of the input element.
Demo & Source Code
Github RepositoryWay to pass data from parent component to child component
- Create react application
- Setup input element in Parent component
- Handle value from parent in Child component
- Output
1. Create react application
First you have to create the startup react application. You may use the create-react-app for same. Please check below link to create react application.
2. Setup input element in Parent component
We will consider App.js file as parent component to setup input element in render method and bind the change event. Also we will manage the input value in state variable.
Now we will import the child component (Child.js) and pass the state value in child component.
Please look at the below code as parent component.
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import React, { Component } from 'react'; import Child from './Child'; class App extends Component { constructor(props) { super(props); this.state = { inputVal: 'Clue Mediator' } this.onInputChange = this.onInputChange.bind(this); } onInputChange(e) { this.setState({ inputVal: e.target.value }); } render() { return ( <div style={{ width: 500, margin: 50 }}> <h3>Parent Component</h3> <hr /> Input: <input value={this.state.inputVal} onChange={this.onInputChange} /> <Child elementValue={this.state.inputVal} /> </div > ); } } export default App; |
3. Handle value from parent in Child component
In child component we can have access the parent value and display it on the page via child component using props.
Child.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import React, { Component } from 'react'; class Child extends Component { render() { return ( <div style={{ margin: '50px 0 50px 50px' }}> <h3>Child Component</h3> <hr /> Input Value: {this.props.elementValue} </div> ); } } export default Child; |