How to set state of sibling components easily in React?

Posted by Jessica Taylor | Updated on

If you want to set state of sibling components easily in React? The parent component should pass a callback to the children, and each child would trigger that callback when its state changes. You could actually hold all of the state in the parent, using it as a single point of truth, and pass the “selected” value down to each child as a prop.

In that case, the child could look like this:

It has no state, it just fires an onToggle callback when clicked. The parent would look like this:

You can see a working example of this here: https://jsfiddle.net/fth25erj/


If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.

Related Questions & Answers