Search code examples
reactjsflux

Changing state in 'uncle' component?


On one of my routes, I have a list of items, which you can click on to get more details in a 'detail' view. Both the list and the detail view are shown simultaneously.

hierarchy:

                   A (page wrapper component)
                 /   \
    (list view) B      C (detail view)
              / | \
(list items) D.....Z 

I have a click event on the D..Z that should change the state in component C, to show the data of the clicked list item

Conceptually, how should this be accomplished, given React's emphasis on a unidirectional dataflow?


Solution

  • You should always try to put state as high up the component tree as you can.

    In your case, the information about which item is currently selected should be stored in the state of your wrapper component, since it is an ancestor of both your detail view component and your list items components.

    Here's an example implementation for your page wrapper component:

    var PageWrapper = React.createClass({
        getInitialState() {
            return {
                selectedItem: null,
            };
        },
    
        _handleItemClick(selectedItem) {
            this.setState({ selectedItem });
        },
    
        render() {
            return (
                <div>
                    <ListView items={[...]} onItemClick={this._handleItemClick} />
                    <DetailView item={this.state.selectedItem} />
                </div>
            );
        },
    });