12/09/2024
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.
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
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": [] } ] } ] } ];
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> ); };
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> ); };
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;
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; }
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!
24/08/2024 | ReactJS
14/09/2024 | ReactJS
22/09/2024 | ReactJS
14/09/2024 | ReactJS
13/07/2024 | ReactJS
14/09/2024 | ReactJS
24/08/2024 | ReactJS
15/08/2024 | ReactJS
16/07/2024 | ReactJS