63

How do I access one component's state in another component? Below is my code and I'm trying to access the state of component a in component b.

var a = React.createClass({
    getInitialState: function () {
        return {
            first: "1"
        };
    },

    render: function () {
        // Render HTML here.
    }  
});

var b = React.createClass({
    getInitialState: function () {
        return {
            second: a.state.first
        };
    },

    render: function () {
        // Render HTML here.
    }  
});

But I'm not getting anything.

Ninjakannon
  • 3,751
  • 7
  • 53
  • 76

6 Answers6

35

Even if you try doing this way, it is not correct method to access the state. Better to have a parent component whose children are a and b. The ParentComponent will maintain the state and pass it as props to the children.

For instance,

var ParentComponent = React.createClass({
  getInitialState : function() {
    return {
      first: 1,
    }
  }

  changeFirst: function(newValue) {
    this.setState({
      first: newValue,
    });
  }

  render: function() {
   return (
     <a first={this.state.first} changeFirst={this.changeFirst.bind(this)} />
     <b first={this.state.first} changeFirst={this.changeFirst.bind(this)} />
   )
 }
}

Now in your child compoenents a and b, access first variable using this.props.first. When you wish to change the value of first call this.props.changeFirst() function of the ParentComponent. This will change the value and will be thus reflected in both the children a and b.

I am writing component a here, b will be similar:

var a = React.createClass({

  render: function() {
    var first = this.props.first; // access first anywhere using this.props.first in child
    // render JSX
  }
}
Naisheel Verdhan
  • 4,905
  • 22
  • 34
18

If two components need access to the same state they should have a common ancestor where the state is kept.

So component A is the parent of B and C. Component A has the state, and passes it down as props to B and C. If you want to change the state from B you pass down a callback function as a prop.

Jeger
  • 490
  • 5
  • 18
8

I would suggest you use a state manager like Redux (personal favorite), MobX reflux, etc to manage your state.

How these works is they allow you to contain all shared state in one state storage (called a store), and whatever component needs access to a part of that shared state, it will just get it from the store.

It looked very hard to get started with but once you get over the small challenges, get 2 or 3 "wtf's" out of the way. It gets easier.

Take a look here: http://redux.js.org/

EDIT: Redux is good but the boilerplate code is really a turn off... for those of you looking for a simpler, more magical (this can be good and bad) solution use mobx : https://mobx.js.org/

Ally Jr
  • 1,055
  • 1
  • 14
  • 27
3

in the child component create function that sets the state:

changeTheState(){
    this.setState({something:"some value"})
}

and in parent component give the child a ref as following:

<Child ref={component => this._child = component}/>

then in parent make a function to access the changeTheState()

parentFunction(){
    this._child.changeTheState();
}

and just use the parentFunction.

slartidan
  • 20,403
  • 15
  • 83
  • 131
Hassan Kandil
  • 1,612
  • 1
  • 13
  • 26
1

If you have A and B component where B is a child of A, you can pass a function to change the state of A though props to B.

function B(props) {
    return <button onClick={props.changeA} />
}

class A extends React.Component {

    //constructor
    //pass this function to B to change A's state
    handleA() {
        this.setState({});
    }

    render() {
        return <B changeA={() => this.handleA()} />
    }
}
minhguy.
  • 11
  • 2
0

Take a look at React Context

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

You can also update Context from a nested component if required.

Kirk Hammett
  • 656
  • 8
  • 24