Learn how to change the state from the parent inside a child component easily in React.

How to update parent state from child component in React

You may want to modify some properties in the state of the parent component from a child component. Although there's no directly way as adding references, like you do when you want to achieve parent-child communication, you can still achieve it indirectly. To achieve the child-parent communication, you can send a function as a Prop to the child component. This function should do whatever it needs to in the component e.g change the state of some property.

Consider the following Parent component:

class Parent extends React.Component {
    constructor(props) {
        super(props)

        // Bind the this context to the handler function
        this.handler = this.handler.bind(this);

        // Set some state
        this.state = {
            messageShown: false
        };
    }

    // This method will be sent to the child component
    handler() {
        this.setState({
            messageShown: true
        });
    }

    // Render the child component and set the action property with the handler as value
    render() {
        return <Child action={this.handler} />
    }
}

The state of this parent component has the messageShown property that we want to change for some reason from the Child component. In the parent we'll render the Child component and we'll send as a property (in this case action) the handler function declared in the parent.

The Child component in this case is very simple, it will draw a button which action Prop (sent in the parent component) will be triggered when the button is clicked:

class Child extends React.Component {
    render() {
        return (
            <div>
                {/* The button will execute the handler function set by the parent component */}
                <Button onClick={this.props.action} />
            </div>
        )
    }
}

In this way you can execute parent functions from your child component easily.

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors