Accessing a component's state from another component

- 1 answer

Ad

Would like a bit of knowledge gain with your help on this one. Just to clarify, I'm still educating myself with Reactjs.

I have two components, A and B. I need to access A's state from B. Is that possible?

var A = React.createClass({
  getInitialState(){
   return {foo: 'bar'}
  },

 ...
});

var B = React.createClass({
  getInitialState(){
   return {x: 'y'}
  },

 render(){
  var a = <A />;
  var b = a.state.foo; // This was just a guess but I dont understand the docs for something like this.
  return({b});
 }
});

In B's component, how to render A's state, which is bar? I wish to have two separate components.

I have been reading about ref but still can't figure out how to accomplish what I want with refs.

React version: 0.14.3

Ad

Answer

Ad

Let's look at the purpose of state and props. A component's state is completely internal to a component. It is never known outside of the component and may/not be passed down to the children components (as props). Props on the other hand are explicitly public and are merely consumed by the component. They should be the only means of passing information down to a component.

While designing your components, always consider this that any data required by more than a single component cannot be a state of any one of them. React encourages unidirectional data flow and accessing state across different components violates that, thereby making your components difficult to reason with.

In your case, since B needs to know some information which A has, I suggest something like this -

  • A publishes this information to a Flux store at an appropriate time.

  • B has subscribed to the same Flux store, it gets notified of this
    information and updates itself.

Ad
source: stackoverflow.com
Ad