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.

Solution 1

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.