Danny Kim Danny Kim - 5 months ago 13
Javascript Question

React - Passing data to Grand parent Component

enter image description here

As above structures , I would like to pass some states to "Left Components" which is Grand-Grand-Grand parent components.

var grandChildRight = React.createClass({
clicksomething : function () {
this.setState({data:'you clicked me'});
}
});

var leftComponent : React.createClass({
render : function () {
{this.props.data}
};
});

HTML
<div class="left">
<leftComponent data="?" />
</div>
<div class="right">
<rightComponent>
<anotherComponent>
<grandChildRight />
</anotherComponent>
</rightCompoent>
</div>


Is any way I can do this without using "Flux" or "Redux".
Please help me out this.

Thanks lot.

Answer

You could try adding container that wraps your HTML and adding a callback prop to grandChildRight for it to call when its state updates:

var grandChildRight = React.createClass({
    clicksomething: function () {
        this.props.onUpdate({data:'you clicked me'});
    }
});

var leftComponent = React.createClass({
    render : function () {
        {this.props.data}
    };
});

var container = React.createClass({
    onRightGrandChildUpdate: function( newState ) {
       this.setState(newState);
    },

    render: function() {
        return (<div className="container">
          <div className="left">
             <leftComponent data={this.state.data} />
          </div>
          <div className="right">
            <rightComponent>
              <anotherComponent>
                <grandChildRight onUpdate={this.onRightGrandChildUpdate.bind(this)} />
              </anotherComponent>
            </rightCompoent>
          </div>
        </div>);
    }
});

(Notice the .bind(this) when passing this.onRightGrandChildUpdate to onUpdate of the grandChildRight component. Doing so ensures this binds to the container component, and not the current global object.)

Then your "HTML" becomes:

<container />

Essentially, this lifts the data you're interested in to a level above both the right grandchild and left component. The supplied onUpdate property allows the right grandchild to update the container's state, which then affects the data passed into the left component.