Expandable Object Tree View

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to create an expandable object tree view in React. This component is useful for displaying complex data structures in a structured and collapsible format. We will use the useState hook and recursion to render a tree view of a JSON object or array with collapsible content. By the end of this lab, you will be able to create and customize a tree view component to display your data in a clear and organized way.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/FundamentalsGroup -.-> react/conditional_render("`Conditional Rendering`") react/FundamentalsGroup -.-> react/list_keys("`Lists and Keys`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38368{{"`Expandable Object Tree View`"}} react/event_handling -.-> lab-38368{{"`Expandable Object Tree View`"}} react/conditional_render -.-> lab-38368{{"`Expandable Object Tree View`"}} react/list_keys -.-> lab-38368{{"`Expandable Object Tree View`"}} react/hooks -.-> lab-38368{{"`Expandable Object Tree View`"}} react/use_state_reducer -.-> lab-38368{{"`Expandable Object Tree View`"}} end

Expandable Object Tree View

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

The following code renders a collapsible tree view of a JSON object or array. By using the useState() hook to create the isToggled state variable, you can determine the initial state of the content (collapsed/expanded) by passing the toggled prop. The appearance of the component is determined based on isParentToggled, isToggled, name, and checking for Array.isArray() on data.

For each child in data, determine if it is an object or array and recursively render a sub-tree or a text element with the appropriate style. To toggle the component state, render a <span> element and bind its onClick event to alter the component's isToggled state.

The CSS styles are defined for the component's appearance, including margin, position, border, and display properties.

const TreeView = ({
  data,
  toggled = true,
  name = null,
  isLast = true,
  isChildElement = false,
  isParentToggled = true
}) => {
  const [isToggled, setIsToggled] = React.useState(toggled);
  const isDataArray = Array.isArray(data);

  return (
    <div
      className={`tree-element ${isParentToggled && "collapsed"} ${
        isChildElement && "is-child"
      }`}
    >
      <span
        className={isToggled ? "toggler" : "toggler closed"}
        onClick={() => setIsToggled(!isToggled)}
      />
      {name ? <strong>&nbsp;&nbsp;{name}: </strong> : <span>&nbsp;&nbsp;</span>}
      {isDataArray ? "[" : "{"}
      {!isToggled && "..."}
      {Object.keys(data).map((v, i, a) =>
        typeof data[v] === "object" ? (
          <TreeView
            key={`${name}-${v}-${i}`}
            data={data[v]}
            isLast={i === a.length - 1}
            name={isDataArray ? null : v}
            isChildElement
            isParentToggled={isParentToggled && isToggled}
          />
        ) : (
          <p
            key={`${name}-${v}-${i}`}
            className={isToggled ? "tree-element" : "tree-element collapsed"}
          >
            {isDataArray ? "" : <strong>{v}: </strong>}
            {data[v]}
            {i === a.length - 1 ? "" : ","}
          </p>
        )
      )}
      {isDataArray ? "]" : "}"}
      {!isLast ? "," : ""}
    </div>
  );
};
.tree-element {
  margin: 0 0 0 4px;
  position: relative;
}

.tree-element.is-child {
  margin-left: 16px;
}

div.tree-element::before {
  content: "";
  position: absolute;
  top: 24px;
  left: 1px;
  height: calc(100% - 48px);
  border-left: 1px solid gray;
}

p.tree-element {
  margin-left: 16px;
}

.toggler {
  position: absolute;
  top: 10px;
  left: 0px;
  width: 0;
  height: 0;
  border-top: 4px solid transparent;
  border-bottom: 4px solid transparent;
  border-left: 5px solid gray;
  cursor: pointer;
}

.toggler.closed {
  transform: rotate(90deg);
}

.collapsed {
  display: none;
}
const data = {
  lorem: {
    ipsum: "dolor sit",
    amet: {
      consectetur: "adipiscing",
      elit: [
        "duis",
        "vitae",
        {
          semper: "orci"
        },
        {
          est: "sed ornare"
        },
        "etiam",
        ["laoreet", "tincidunt"],
        ["vestibulum", "ante"]
      ]
    },
    ipsum: "primis"
  }
};
ReactDOM.createRoot(document.getElementById("root")).render(
  <TreeView data={data} name="data" />
);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Expandable Object Tree View lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like