Having difficulty constructing the tree hierarchy in a React project

Trying to implement a tree view in React but struggling with constructing the hierarchical view of information.

Reference: https://www.w3schools.com/howto/howto_js_treeview.asp

Example on CodeSandbox: https://codesandbox.io/s/unruffled-babbage-9knrz?file=/index.js

JSON example (format may vary):

const data = [
  {
    title: "Node 1",
    childNodes: [
      { title: "Childnode 1.1" },
      {
        title: "Childnode 1.2",
        childNodes: [
          {
            title: "Childnode 1.2.1",
            childNodes: [{ title: "Childnode 1.2.1.1" }]
          },
          { title: "Childnode 1.2.2" }
        ]
      }
    ]
  }
];

I have a toggle function for expanding/collapsing tree nodes, but still having difficulty with building the tree in react.

Any guidance would be appreciated.

Answer №1

Start by utilizing <Node/> instead of <Tree/> as the recursive component in your React project.

Avoid using querySelector and classList to modify the state of a component in React.

You can check out my implementation in the code example here

const Tree = () => {
  return (
    <ul>
      {data.map(({ title, childNodes }) => (
        <Node key={title} title={title} childNodes={childNodes} />
      ))}
    </ul>
  );
};

class Node extends React.Component {
  state = {
    isOpen: false
  };
  toggle = () => {
    this.setState({
      isOpen: !this.state.isOpen
    });
  };
  render() {
    const { title, childNodes } = this.props;
    const { isOpen } = this.state;

    return (
      <li>
        <span className="caret" onClick={this.toggle}>
          {title}
        </span>
        {childNodes && isOpen && (
          <ul>
            {childNodes.map(({ title, childNodes }) => (
              <Node key={title} title={title} childNodes={childNodes} />
            ))}
          </ul>
        )}
      </li>
    );
  }
}

export default Tree

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with the functionality of jQuery append and AngularJS ng-if not functioning

In my application using checkboxes, I control the visibility of charts with the ng-if directive and implement drag-and-drop functionality with angular-Dragula. The use of ng-if is essential for me as it allows me to manipulate visible div IDs and organize ...

What is the advantage of using require() over url/path for displaying images in react native?

What is the rationale behind using require() rather than directly using the URL or path of an image to display images in React Native? Is there a specific advantage to using require()? ...

Leveraging CSS to automatically number nested sections

Assume we have an example HTML or XML document structured like this: <body> <section> <h1>This should be numbered 1</h1> <section> <h1>This should be numbered 1.1</h1> <p>blah& ...

Loading images in advance using jCarousel

I need help with preloading images on a jCarousel that loads a JSON feed and generates necessary HTML. Can anyone suggest a way to accomplish this task efficiently? $(".banner ul").jcarousel({ itemLoadCallback:loadTopBanner, auto: 6, wrap: ...

Can process.env.NODE_ENV be found within Azure App Service?

I am integrating NodeJS with my Angular application using ExpressJS. I came across an npm package called norobot that I want to install in order to utilize the process object. I need guidance on how and where to set the NODE_ENV in an App Service on Micro ...

Using React, implement nested fetch calls to make multiple AJAX requests

Upon executing a function, it retrieves all zones in an environment and then proceeds to make an API call for the border points of each zone. While all fetches are successfully executed, there's a problem arise in the then block for the initial fetch ...

Exploring the versatility of Angular by creating various flex layouts with Angular Material cards

I'm struggling to implement the design shown below using cards and a flex layout in a responsive way. I've tried working on it using StackBlitz but haven't been able to get it right - the margin and layout get messed up on different screens. ...

Unleashing the potential of an endless animation by incorporating pauses between each iteration

I am trying to create an infinite animation using animate css but I want to add a delay between each iteration. After exploring various options, I first attempted to achieve this using plain JavaScript. Here is the HTML snippet: <div id="item" class= ...

Why is it not possible to return a header in a Typescript function?

I am new to using typescript and I have encountered an issue with a value for headers. Initially, it worked fine when directly set in the code. However, when I attempted to move it into a separate function that could be called, the functionality broke. Be ...

One crucial factor to consider when dealing with dual screen setups is the

Imagine you have the following code snippet : <ul> <li>Menu1 <ul class="submenu"> <li class="firstmenu">submenu-1</li> <li>submenu-2</li> < ...

Implementing a 'click tracking' feature for a toggle button in a React application

After successfully implementing a star button next to each comment on my message board, I now want to add a counter that keeps track of how many comments have been favorited. The challenge lies in properly counting the true/false status of all the stars. ...

Get a file from a distinct internal server than the one where the website is operating

I am trying to download a file from an internal server that is separate from the one where the website is hosted. I have attempted various methods such as... <a href="javascript:Start('file://servername/path/filename.txt')> <a href="// ...

Comparing various object fields to a single input value in JavaScript

I have a challenge with filtering a large dataset of products based on user input values. Here is an example of my product dataset: const products = [ {id: 0, name: "Product1", brand: "Theraflu", itemCode: "THE110", price: 5 ...

Visual Studio Code unable to locate source maps for typescript debugging

Looking for some help debugging a basic Hello World TypeScript file. Whenever I try to set a breakpoint, it seems like VS Code is having trouble locating the source map, even though it's saved in the same directory. I'm using Chrome as my browser ...

Issue with the functionality of Jquery scrolling through thumbnail images animation

I have encountered an issue related to the previous question that I posted here. After successfully implementing the provided solution, it initially seemed to be working. However, when I clicked the next button and reached the 3rd click, the jQuery scrolli ...

Implementing a Searchable Autocomplete Feature within a Popover Component

Having an issue saving the search query state. https://i.stack.imgur.com/HPfhD.png https://i.stack.imgur.com/HbdYo.png The problem arises when the popover is focused, the searchString starts with undefined (shown as the second undefined value in the ima ...

Arranging Pictures Beside Text Using CSS

I have a puzzling issue that I cannot seem to find an answer for despite the countless times it has been asked. In my footer, there is aligned copyright text, and I am attempting to add 3 logos to the right of it without any line breaks. However, when the ...

eliminate gaps between hyperlinks using cascading style sheets

I developed a webapp for iOS which has a specific page containing a centered div with 3 buttons. Inside this div, there is a total of 460px with each link measuring as follows: the first and last are 153px while the middle one is 154px. The main issue ar ...

Is it possible to include a local directory as a dependency in the package.json file

As I work on developing an npm package alongside its application, I find myself constantly making small changes to the package. Each time I make a change, I want to run the application again for testing purposes. The package is included as a dependency in ...

When starting a new project in React, npm can sometimes throw an error stating `'ENOENT: no such file or directory'`

I recently downloaded Node.js on a Windows system and attempted to start a new React project using npm. However, when I enter the command 'npx create-react-app projectName', an error message pops up: ENOENT: no such file or directory, lstat &apo ...