How to set one component’s state from another component in React

Welcome to SO!

Setting the parent state from the child:

If you want your child component to have access to your parent component’s state, just pass setState() as a prop in your parent class, like so…

<PostForm
    setParentState={(state) => this.setState(state)}
/>

Then, later in PostForm.js, just set the parent state like so….

this.props.setParentState(newParentStateObject);

Or, you can even just do….

<PostForm
    postform={this}
/>

And later on, you can call anything in postform with this.props.postform.anyFunctionEver().

Setting the child state from the parent:

Suppose you want to do the opposite now: update the state of the child component from the parent? That’s just as easy, set a reference when defining <PostForm/>

<PostForm
    ref={(instance) => {this.postform = instance}}
/>

Then you can set the postform’s state directly in your parent class…

this.postform.setState(newChildStateObject);

A lot can happen with the state, so if you’re not sure, try making a testFunc() {console.log('test');}, and then try passing/activating this between parent and child.

Leave a Comment