Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access one component's state from another component

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.

like image 357
Vamshi Krishna Lakkars Avatar asked Apr 25 '16 10:04

Vamshi Krishna Lakkars


People also ask

How can we access one component state in another component?

To pass the state into another component, you can pass it as a prop. Then, inside <ExampleComponent /> , you can access the data as this. props.

Can we use state in another component?

To use the same state in several components, you have to: Lift the state up to the closest common ancestor. Pass down the state variable and the function to update this state in the props.


2 Answers

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   } } 
like image 73
Naisheel Verdhan Avatar answered Sep 17 '22 15:09

Naisheel Verdhan


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.

like image 23
Jeger Avatar answered Sep 16 '22 15:09

Jeger