In a composited component, how can child access the state property of top most

- 1 answer

Ad

For simplification, I have a a component, that includes a subcomponent. The top parent component is the only stateful compontent. But the state of this needs to be set on children deep within. How can these children access the state of the top most parent?

Is passing the state down via props the only way? I ask because I have a comonent that has many children deep down, so to access state I would have to pass state as a prop to 5 levels, just so 5th level can access state.

For a simplified example:

var Timer = React.createClass({
  getInitialState: function() {
    return {secondsElapsed: 0};
  },
  tick: function() {
    this.setState({secondsElapsed: this.state.secondsElapsed + 1});
  },
  componentDidMount: function() {
    this.interval = setInterval(this.tick, 1000);
  },
  componentWillUnmount: function() {
    clearInterval(this.interval);
  },
  render: function() {
    return (
      <Label />
    );
  }
});

var Label = React.createClass({
  render: function() {
    return (
      <div>Seconds Elapsed: {this.state.secondsElapsed}</div>
    );
  }
});

ReactDOM.render(<Timer />, mountNode);

This example gives this.state is null

Ad

Answer

Ad

There are in general two well accepted ways to do this.

  1. Indeed pass the properties down the tree of components. This can sometimes work very well, and is something I personally use a lot for more UI work in the components, like making sure a pagination works generically all over the app (total pages, currentpage, items per page). For more app 'state' kind of things this is generally not the right approach
  2. Switch to something to manage your application state, like Flux, which will help you with the concept of a store to keep this state in, if both components need this. I use the alt implementation, but Facebook's official and other ones are also very well known.

In general I'd advise you to dive a bit into some videos of React and Flux, perhaps the ones where people show you how they do certain things like this. For example this one.

Ad
source: stackoverflow.com
Ad