logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Creating Metadata Driven Tree Structure in React JS

author
Written by
Abhishek Goyan

12/09/2024

React

Sign in to read full article

Tree structures are a popular way to represent hierarchical data. From file explorers to category trees in web applications, they help users navigate complex datasets intuitively. In this post, we will create a tree component in React that will render based on a nested JSON input while adding functionalities for searching, expanding, and collapsing the nodes.

Step 1: Setting Up the Project

To get started, we need to set up a React environment. If you don’t have one, you can easily create a new React app using Create React App:

npx create-react-app tree-structure cd tree-structure npm start

Step 2: Defining the JSON Structure

First, let’s define a sample JSON input that represents a tree structure. We’ll include various nested nodes to illustrate both a simple and complex structure.

const treeData = [ { "id": 1, "name": "Root", "children": [ { "id": 2, "name": "Child 1", "children": [] }, { "id": 3, "name": "Child 2", "children": [ { "id": 4, "name": "Grandchild 1", "children": [] }, { "id": 5, "name": "Grandchild 2", "children": [] } ] } ] } ];

Step 3: Building the Tree Component

Now, let’s create a component that will take treeData as props and render the tree structure.

import React, { useState } from 'react'; // TreeNode component for rendering each node of the tree const TreeNode = ({ node }) => { const [isExpanded, setIsExpanded] = useState(false); const toggleExpand = () => { setIsExpanded(!isExpanded); }; return ( <div style={{ marginLeft: '20px' }}> <div onClick={toggleExpand} style={{ cursor: 'pointer' }}> {node.children.length > 0 && (isExpanded ? '− ' : '+ ')} {node.name} </div> {isExpanded && node.children.map(childNode => ( <TreeNode key={childNode.id} node={childNode} /> ))} </div> ); }; // Main Tree component const Tree = ({ data }) => { return ( <div> {data.map(node => ( <TreeNode key={node.id} node={node} /> ))} </div> ); };

Step 4: Adding Search Functionality

Next, we need to implement search functionality that allows users to filter nodes based on their names.

const TreeWithSearch = ({ data }) => { const [searchQuery, setSearchQuery] = useState(''); const [filteredData, setFilteredData] = useState(data); const handleSearchInputChange = (e) => { const query = e.target.value; setSearchQuery(query); const searchResults = data.filter(node => node.name.toLowerCase().includes(query.toLowerCase()) ); setFilteredData(searchResults); }; return ( <div> <input type="text" value={searchQuery} onChange={handleSearchInputChange} placeholder="Search..." /> <Tree data={filteredData} /> </div> ); };

Step 5: Integrating Everything in the App Component

Finally, we will utilize the TreeWithSearch component in our main App component, which will render everything on the screen.

const App = () => { return ( <div> <h1>Interactive Tree Structure</h1> <TreeWithSearch data={treeData} /> </div> ); }; export default App;

Styling the Tree

For better aesthetics, we can add some basic CSS styling to improve the appearance of our tree.

div, input { font-family: Arial, sans-serif; } input { padding: 10px; margin-bottom: 20px; border: 1px solid #ccc; border-radius: 4px; }

Running the Application

To see everything in action, make sure to run your React application. You should be able to expand and collapse the nodes of the tree and use the search bar to find specific entries!

By implementing these steps, we have successfully created an interactive tree structure in React that takes JSON input, and allows for searching, expanding, and collapsing functionalities. You can extend this basic structure in many ways, such as adding more features like editing nodes, removing nodes, or even integrating drag and drop functionalities. Happy coding!

Popular Tags

ReactJSONUI

Share now!

Like & Bookmark!

Related Collections

  • Mastering React Concepts

    24/08/2024 | ReactJS

  • React Interview Challenges: Essential Coding Problems

    14/09/2024 | ReactJS

Related Articles

  • Understanding the Virtual DOM in React.js

    28/11/2024 | ReactJS

  • Introduction to React: Understanding the Basics

    24/08/2024 | ReactJS

  • Build a Custom Modal Component in React

    14/09/2024 | ReactJS

  • Handling Events in React: A Comprehensive Guide

    24/08/2024 | ReactJS

  • Creating a Drag-and-Drop Feature in React

    14/09/2024 | ReactJS

  • Advanced Hooks: Mastering useContext in React

    24/08/2024 | ReactJS

  • Build a Protected Route Component Using React Router

    14/09/2024 | ReactJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design