[React] Passing Data Between React Components

Andrew Samchuk
Nov 2 · 2 min read

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

  1. 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

  1. Create the updateData function in the parent. It has an input parameter value, we assign this parameter to the state of our component using the setState function.
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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade