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:
1 2 3 4 5 6 7 8 9 | var Child = React.createClass({ onToggle: function() { this.props.onToggle(this.props.id, !this.props.selected); }, render: function() { return <button onClick={this.onToggle}>Toggle {this.props.label} - {this.props.selected ? 'Selected!' : ''}!</button>; } }); |
It has no state, it just fires an onToggle callback when clicked. The parent would look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | var Parent = React.createClass({ getInitialState: function() { return { selections: [] }; }, onChildToggle: function(id, selected) { var selections = this.state.selections; selections[id] = selected; this.setState({ selections: selections }); }, buildChildren: function(dataItem) { return <Child id={dataItem.id} label={dataItem.label} selected={this.state.selections[dataItem.id]} onToggle={this.onChildToggle} /> }, render: function() { return <div>{this.props.data.map(this.buildChildren)}</div> } }); |
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.