I have just started using React and I am struggling to figure out how to make 2 components communicate between each other to exchange data. For example, I am trying to build a calculator which has component buttons with their values and component input field which is supposed to display the value of the buttons. I think I can figure out how to write the code, but I am strugging to understand, how to make them know about each other? Thank you!
-
2Does this answer your question? [ReactJS Two components communicating](https://stackoverflow.com/questions/21285923/reactjs-two-components-communicating) – takendarkk May 28 '20 at 14:20
4 Answers
1) Define state and handler at parent component 2) send them to 2 child components as props. 3) Once the state is changed by either of 2 child components, the changes affect immediately. I hope this will help you.

- 335
- 1
- 8
You can do that via 2 ways
1 - props to communicate between them
class Calculator extends React.Component {
this.state ={
num1:1,
num2:2
}
render() {
return <Sum num1={this.state.num1} num2={this.state.num2}>;
}
}
const sum =(props)=>{
return (
<div>
{props.num1+props.num2}
</div>
);
}
2 - You can use any State management solution for react (but only if its a complex app)

- 296
- 3
- 10
If you have two components (let's call them A and B), you can make them "talk" between each other, by defining a context in one of their common parents, or even to the root of the app. Then you can subscribe to this context (useContext) from both of A and B, and push data into the context, whenever you wish. This will trigger a re-render of all components which are using this context, and they will then get this updated data.
Using common state in the parent and passing it as props to A and B is also fine, but my proposal to do it with context is covering the cases where A and B are not siblings in the Virtual DOM tree, e.g. it's hard to pass props to them, from the parent, but it's super easy to do so by simply using a common context.
Hope this answers to your question! :)

- 181
- 7
Coming from OOP, I tend to prefer the simple createRef() approach as a way to expose the methods of a component to another in a simple way.
Here's below a very simple example:
class MyComponent extends Component {
constructor(props) {
this.compRef = React.createRef()
}
onSomething = (val) => {
this.compRef.current.setState({key: val})
}
render() {
return (
<SomeComponent ref={this.compRef} />
<SomeOtherComponent onChange={this.onSomething} />
)
}
}

- 618
- 5
- 14