How React components talk to each other

Yesterday, we said that the easiest way to make components talk to each other is to hoist their state up one level or multiple levels, and then pass props down; and callbacks go back up to change the shared state, which then gets propagated to everybody who cares about that state.

Now let me show how that looks in code.

We're going to take our button and make it relate it to another component and make them both react to being hovered upon.

So we have the button that turns red when you mouse-over it. To make the comment also turn red we have to hoist the current background state. We're going to call it a "hovered" state, and hoist it up to our app.js.

We have to move it out of background ... out of state in button, and we're going to define background hovered. Then it's red, otherwise it's white.

And we go up to our state. We say hovered ... let's say hoveredMessages. We only have two so far, so we're going to say the first one is false and the second one is also false.

Then we go into our button and we say hovered equals ...

So now we're passing the hovered state down into our button. Change our mouseOver and mouseOut event handlers to instead of calling this set state, they're going to call callbacks that are passed down as props. That's gonna look like this. This props on onHover, and we also remove this.setState.

Now we have to pass these down as props so that they can be callbacks into our parent component.

We have to define those two functions, just like we did before for event handlers. And each of those is going to set state, copies the hovered messages object, and makes a new one.

Now we should have a button that still turns red ... and it does.

To make the message turn red as well we have to go into our messages, loop pass into each message whether it is hovered right now. And in the message component, which is still in the same file, we're going to take hovered from our props and say that background is if it's hovered, the background is red, otherwise it's white.

There you go.

And that's how you make components talk to each other without any Redux or MobX or anything like that.

Know someone who wants to learn React and its whole ecosystem? Share 👇