svoruganti
svoruganti

Reputation: 672

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

Say I have the following component named Home:

this.state = {
    posts: []
}
componentDidMount() {
    ... data is fetched from api
}

<div
    <PostForm />
    {this.state.posts.map(post => (
     <Post key={post.id} post={post} />
    ))}
</div>

How would I update the state of Home, or re fetch data from the api after the the PostForm component is submitted with a new Post.

Upvotes: 1

Views: 2156

Answers (1)

HoldOffHunger
HoldOffHunger

Reputation: 20851

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.

Upvotes: 4

Related Questions