[React] Passing Data Between React Components
In a reaction, the data stream is unidirectional. This means that the data is transmitted as a waterfall, from top to bottom, from parent to child, through props. What are props? This is an immutable read-only object. It’s easier to understand if you think of components as functions (and they are essentially them), props is just an argument to a function that we can work with internally, but not change it.
Parent to Child — Use Prop
- In the parent component, we transfer data from the state to the child.
class ParentComponent extends React.Component {
state = {
name: 'Peter'
}; render() {
return (
<div>
<p>State: {this.state.name}</p>
<ChildComponent name={this.state.name} />
</div>
)
}
}
2. In the child accept and display.
class ChildComponent extends React.Component {
render() {
return (
<div>
<p>Props: {this.props.name}</p>
</div>
)
}
}Child to Parent — Use a callback and states
- Create the
updateDatafunction in the parent. It has an input parametervalue, we assign this parameter to the state of our component using thesetStatefunction.
class ParentComponent extends React.Component {
state = {
name: 'Parent value'
}; updateData = (value) => {
this.setState({ name: value })
} render() {
return (
<div>
<p>State: {this.state.name}</p>
<ChildComponent updateData={this.updateData} />
</div>
)
}
}
2. We pass the updateData function to the child through props. I created a button in a child element, when I click on it, a function will be called that we passed using props. A new parameter for the text is passed to her, and we want to pass it to the parent.
class ChildComponent extends React.Component {
state = {
name: 'Child value'
} render() {
return (
<div>
<button onClick={() => { this.props.updateData(this.state.name)}}>Change value</button
</div>
)
}
}
Between Siblings — Combine the above
In order to transfer data between neighboring components, you need to use an intermediary — their parent. First you need to pass the data from the child to the parent as an argument to the callback. Then assign this data to the parent’s state and pass through props to another component.
