Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Manage State in a Tree Component in ReactJS

Apr 10, 2020 • 6 Minute Read

Introduction

State and props are essential concepts of a React app. If you have to send data from one component to another, then these two are imperative in passing and accessing the data.

This guide will explain how to manage the state in an app. In almost all apps, you are going to have multiple components like a tree structure. You need to pass the data from the parent to the child and get the response from the child, which will affect other child components.

Summary

  • Introduction to state
  • Role of state in an app
  • Manage the state in an app

Introduction to State

The state is a variable like other variables in a JavaScript app. It is only accessible inside a component. You can pass the state to other child components, and you can also change the state from the child components.

The props store the data passed from the parent to the child component. You can access the parent data with the help of the props.

One key point of props is that their value cannot be changed. You need to update the state of the parent component to change the props of the child component.

Role of State

The state is used to track the changes in the component. If the value of the state changes, then the render process of the component starts again to reflect the changes in the browser.

You need to change the state to render the app after making changes.

Managing the State in an App

In React, if you have to pass the data from one component to another component, then you need to use the state to pass from the parent and props to get the parent data.

Initially, you have only one component, AppComponent.

For this demo, you'll create an accordion. It is going to be a simple app with a couple of lists. Don't bother with CSS or the look and feel part; this guide focuses on the concepts around state management.

First, create a parent component. Create the state and send it to the child component as props.

Parent.js

      import React, { useState } from "react";
import Child from "./Child";

function Parent() {
  const [state, setState] = useState([
    {
      title: "First Item",
      description: "This is the first item",
      isOpen: false
    },
    {
      title: "Second Item",
      description: "This is the Second item",
      isOpen: false
    },
    {
      title: "Third Item",
      description: "This is the Third item",
      isOpen: false
    }
  ]);
  return (
    <ul>
      {state.map((item, index) => {
        return (
          <li>
            <Child item={item} arr={state} setItem={setState} />
          </li>
        );
      })}
    </ul>
  );
}

export default Parent;
    

In the above code, the useState hook is used to create a variable for state and a function to change the state. If you're not familiar with this, you can learn more here.

To the useState() function, pass an array, which will be the initial value of the state. In the array, you will have a couple of objects with three fields: title, description, and isOpen.

Using the array of the state, make an unordered list. Use the map() method to create a list of child components in which you'll pass the item, array, and setState function.

Next, create the child component.

Child.js

      import React from "react";

function Child(props) {
  let { item, arr, setItem } = props;

  function onToggle(it) {
    let newArr = arr.map(data => {
      data.isOpen = data.title == it.title;
      return data;
    });
    setItem(newArr);
  }
  return (
    <div key={item.title}>
      <label onClick={() => onToggle(item)}>{item.title}</label>
      {item.isOpen && <p>{item.description}</p>}
    </div>
  );
}

export default Child;
    

In the child component, you're accepting the props. As mentioned earlier, the props will store the data of the state.

The item is the current index data. The arr is a whole array, and setItem is the function to change the value of the state of the parent component.

In the return block of the child component, create a div block with a label to display the title of the list and a paragraph tag(p) that shows the description for the list.

The description depends on isOpen to render on the browser. It is toggled by clicking on the title of the list. Call the onToggle() function when the user clicks on the title.

In the onToggle() method, compare the title, assuming that you have a unique title in the array. If the item's title matches with one of the titles from the items in the array, then the value of isOpen of that item will be true. Otherwise, it will be false.

After setting the value of isOpen, update the value of the state using the modified array.

Add the following code to your App.js file.

App.js

      import React from "react";
import Parent from "./components/Parent";

function App() {
  return (
    <div className="App">
      <Parent />
    </div>
  );
}

export default App;
    

Render the Parent component in the App component.

Your app is ready to run. Hit the command npm start in your CLI.

Conclusion

The state is the only way you can communicate with the other components. There are many different methods to manage a state in React. You can use third-party state management libraries like redux, or mobx. The discussed method in the guide is very fundamental and native to core React, so it's important to understand the concept.

That was it from this guide! Continue exploring more on state and its usage to create great apps.