Lone Creation
Lone Creation

Reputation: 69

How can I make two components communicate in React?

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!

Upvotes: 0

Views: 302

Answers (4)

Olivier Lépine
Olivier Lépine

Reputation: 668

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} />
      )
   }

}

Upvotes: 1

Todor Popov
Todor Popov

Reputation: 181

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! :)

Upvotes: 1

royalbhati
royalbhati

Reputation: 306

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)

Upvotes: 1

TopWebGhost
TopWebGhost

Reputation: 335

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.

Upvotes: 1

Related Questions