If you want to make a shared state between two react components? What you want is to implement some object that stores your state, that can be modified using callback functions. You can then pass these functions to your React components.
For instance, you could create a store:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function Store(initialState = {}) { this.state = initialState; } Store.prototype.mergeState = function(partialState) { Object.assign(this.state, partialState); }; var myStore = new Store(); ReactDOM.render( <FirstComponent mergeState={myStore.mergeState.bind(myStore)} />, firstElement ); ReactDOM.render( <SecondComponent mergeState={myStore.mergeState.bind(myStore)} />, secondElement ); |
Now, both the FirstComponent and SecondComponent instances can call this.props.mergeState({ . . .}) to assign state to the same store. I leave Store.prototype.getState as an exercise for the reader.
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.