introduction
Tree View is a common UI component used to display data with hierarchical structures. In React, implementing a tree component can not only improve the user experience, but also make data presentation clearer. This article will build a simple React tree component from scratch, discussing common problems, easy mistakes and how to avoid them, and provide code examples.
Environmental preparation
Before you begin, make sure that the following tools are installed in your development environment:
- and npm
- Create React App
Create a project
First, create a new React project using the Create React App:
npx create-react-app react-tree-view cd react-tree-view
Building basic tree components
Define the data structure
Suppose we have a simple tree data structure, each node contains id, name, and children attributes.
const treeData = [ { id: 1, name: 'Node 1', children: [ { id: 2, name: 'Node 1.1', children: [ { id: 3, name: 'Node 1.1.1' } ] }, { id: 4, name: 'Node 1.2' } ] }, { id: 5, name: 'Node 2', children: [ { id: 6, name: 'Node 2.1' } ] } ];
Create a tree component
Create a folder components in the src directory and create it in it:
import React from 'react'; const TreeNode = ({ node, onToggle }) => { const hasChildren = && > 0; const [isExpanded, setIsExpanded] = (false); const handleToggle = () => { setIsExpanded(!isExpanded); onToggle(, !isExpanded); }; return ( <div style={{ paddingLeft: 20 }}> <div onClick={handleToggle} style={{ cursor: 'pointer' }}> {hasChildren ? (isExpanded ? '-' : '+') : ''} {} </div> {isExpanded && ( <ul> {((child) => ( <TreeNode key={} node={child} onToggle={onToggle} /> ))} </ul> )} </div> ); }; const TreeView = ({ data }) => { return ( <div> {((node) => ( <TreeNode key={} node={node} onToggle={() => {}} /> ))} </div> ); }; export default TreeView;
Using tree components
Use TreeView component in:
import React from 'react'; import TreeView from './components/TreeView'; const treeData = [ { id: 1, name: 'Node 1', children: [ { id: 2, name: 'Node 1.1', children: [ { id: 3, name: 'Node 1.1.1' } ] }, { id: 4, name: 'Node 1.2' } ] }, { id: 5, name: 'Node 2', children: [ { id: 6, name: 'Node 2.1' } ] } ]; function App() { return ( <div className="App"> <h1>Tree View</h1> <TreeView data={treeData} /> </div> ); } export default App;
Frequently Asked Questions and Prone to Mistakes
1. The hierarchy is too deep
Problem Description: Recursive rendering can cause performance issues when the tree structure is very deep.
Workaround: Use virtualization techniques such as react-window to optimize rendering performance.
2. Complex state management
Problem Description: As the complexity of the tree structure increases, state management becomes more and more complex.
Workaround: Use Redux or React Context to centrally manage state and avoid state transfer between components.
3. Improper handling of events
Problem Description: Unexpected behavior may result when node expansion and collapse events are processed without properly managed state.
Workaround: Ensure that the state of each node is managed independently and events are handled uniformly in the parent component.
const TreeNode = ({ node, onToggle, isExpanded }) => { const hasChildren = && > 0; const handleToggle = () => { onToggle(); }; return ( <div style={{ paddingLeft: 20 }}> <div onClick={handleToggle} style={{ cursor: 'pointer' }}> {hasChildren ? (isExpanded ? '-' : '+') : ''} {} </div> {isExpanded && ( <ul> {((child) => ( <TreeNode key={} node={child} onToggle={onToggle} isExpanded={isExpanded} /> ))} </ul> )} </div> ); }; const TreeView = ({ data }) => { const [expandedNodes, setExpandedNodes] = ([]); const handleToggle = (id) => { setExpandedNodes((prev) => { if ((id)) { return ((nodeId) => nodeId !== id); } else { return [...prev, id]; } }); }; const isNodeExpanded = (id) => (id); return ( <div> {((node) => ( <TreeNode key={} node={node} onToggle={handleToggle} isExpanded={isNodeExpanded()} /> ))} </div> ); };
4. Style issues
Problem description: The default style may not meet the requirements and requires a custom style.
Workaround: Use CSS or CSS-in-JS libraries (such as styled-components) to customize the style.
import styled from 'styled-components'; const TreeNodeContainer = ` padding-left: 20px; cursor: pointer; `; const TreeNode = ({ node, onToggle, isExpanded }) => { const hasChildren = && > 0; const handleToggle = () => { onToggle(); }; return ( <TreeNodeContainer onClick={handleToggle}> {hasChildren ? (isExpanded ? '-' : '+') : ''} {} {isExpanded && ( <ul> {((child) => ( <TreeNode key={} node={child} onToggle={onToggle} isExpanded={isExpanded} /> ))} </ul> )} </TreeNodeContainer> ); };
in conclusion
Through this article, we built a simple React tree component from scratch and discussed common problems, easy-to-miss points and how to avoid them.
This is the end of this article about the specific use of React Tree Component Tree View. For more related React Tree Component Tree View, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!