Reactjs how to change the state of a component from a different component Reactjs how to change the state of a component from a different component reactjs reactjs

Reactjs how to change the state of a component from a different component


Components don't publicly expose their state. It's also important to remember that the state is scoped to the instance of components, not their definition.

To communicate between components, you could roll your own event subscription service.

var events = new EventEmitter();// inside Component1events.emit('change-state', newState);// inside Component2events.on('change-state', function(state) {  this.setState(state);});

However, this will quickly become difficult to manage.

A more sensible solution is to use Flux. It allows you to explicitly manage the state of your entire application and subscribe to changes in different bits of the state, within your components. It's worth trying to wrap your head around it.

The component that wants to communicate should dispatch an action and this action will be responsible for changing something in the stores, your other component should subscribe to that store and can update its state based on the change.


You can use a shared state between the two component. You can build a "mixin" like that

app.mixins.DateMixin = {   getInitialState: function ()       return {          dates: []         }      }};

and then in you components you can include this mixins using the mixins array

define([..., /path/component_2.jsx], function(..., Component2) {   var Component1 = React.createClass({      mixins: [app.mixins.DateMixin],      getInitialState: function() {         return {.......};      },      componentDidMount: function() {          .......          dates = ....;          this.setState({dates: dates});      }       render: function() { return (<div ...></div>) }   });}define([..., ], function(...) {   mixins: [app.mixins.DateMixin],   var Component2 = React.createClass({      getInitialState: function() {         return {.......};      },      render: function() { return (<div ...></div>) }   });}

Now your components share the "dates" state and you can change/check it in both of them. NB: you can also share methods with in the same way by writing into a mixin component.

Edit: I suggest you to visit this website http://simblestudios.com/blog/development/react-mixins-by-example.html