← All posts about JavaScript

Update Parent and Child Components State in React.js

May 08, 2020

Thumbnail

When you nest your components in react.js, in some cases, you may want to update the state of the parent component from the child component or vice versa. To achieve this sort of communication you can simply use props and references. If you are using packages such as redux then it is better to centralize the state of your application.

In this article we will update states in both directions for parent and child class components. Assuming you are familiar with JavaScript ES6 features.

Let’s create a new project for this quick tutorial by running the following command in our projects folder:

npx create-react-app my-app

Open the app.js file, in my-app folder, and create the following components that represent the parent and child components.

import React from "react";

function App() {
  Return <ParentComponent />
}

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: "Foo" };
  }
  render() {
    return (
      <div>
        {this.state.value}
        <ChildComponent/>
      </div>
    );
  }
}

The previous component, which is the parent, will display “Foo” followed by “Bar” from the following child component.

class ChildComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = { value: "Bar" }
  }
  render() {
    return <div>{this.state.value}</div>
  }
}

Our aim is to update Foo value from the child component, and Bar value from parent component, in order to do this, we will create a reference for the child component which allows access to the child state, and a prop which contains a function that changes the parent state.

class ParentComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = { value: "Foo" }
  }
  render() {
    return (
      <div>
        {this.state.value}
        <ChildComponent
          ref={ref => (this.child = ref)}
          setState={state => this.setState(state)}
        />
        <button onClick={() => this.child.setState({ value: "Foo" })}>
          Update child state
        </button>
      </div>
    )
  }
}

And finally the buttons that trigger the setState functions in both components.

class ChildComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = { value: "Bar" }
  }
  render() {
    return (
      <div>
        {this.state.value}
        <button onClick={() => this.props.setState({ value: "Bar" })}>
          Update parent state
        </button>
      </div>
    )
  }
}

Chafik Gharbi Web and mobile app developer interested in everything related to JavaScript Follow me on Twitter

© 2020 Chafik Gharbi