Categories
React Answers

How to update the parent’s state in React?

Spread the love

In React, you can update the state of a parent component from a child component by passing down a function as a prop to the child component.

The child component can then call this function, which updates the state in the parent component.

Here’s how we can do it:

ParentComponent.js:

import React, { Component } from 'react';
import ChildComponent from './ChildComponent';

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      parentState: 'initial value'
    };
  }

  // Function to update the parent state
  updateParentState = (newValue) => {
    this.setState({ parentState: newValue });
  }

  render() {
    return (
      <div>
        <ChildComponent updateParentState={this.updateParentState} />
        <p>Parent State: {this.state.parentState}</p>
      </div>
    );
  }
}

export default ParentComponent;

ChildComponent.js:

import React, { Component } from 'react';

class ChildComponent extends Component {
  handleClick = () => {
    // Call the function passed from the parent component to update its state
    this.props.updateParentState('new value');
  }

  render() {
    return (
      <button onClick={this.handleClick}>Update Parent State</button>
    );
  }
}

export default ChildComponent;

In this example, the ParentComponent has a state variable called parentState.

The updateParentState function in the ParentComponent updates the parentState when called.

The ChildComponent receives the updateParentState function as a prop from the ParentComponent.

When the button in the ChildComponent is clicked, it calls the updateParentState function passed down from the ParentComponent, which updates the parent’s state.

This pattern allows child components to interact with and modify the state of their parent components in React applications.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *