EN
React - simple tree component
10 points
In this short article, we would like to show how to create a simple tree component in React.

Practical example:
xxxxxxxxxx
1
// import React from 'react';
2
// import ReactDOM from 'react-dom';
3
4
const nodeStyle = {
5
padding: '4px 0',
6
fontFamily: 'Arial',
7
fontSize: '13px'
8
};
9
10
const headStyle = {
11
display: 'flex',
12
cursor: 'pointer'
13
};
14
15
const wrapperStyle = {
16
width: '20px',
17
};
18
19
const expanderStyle = {
20
border: '1px solid #ebb2b2',
21
borderRadius: '2px',
22
background: '#ffff8a',
23
width: '15px',
24
height: '15px',
25
textAlign: 'center',
26
lineHeight: '15px'
27
};
28
29
const nameStyle = {
30
margin: '0 0 0 6px',
31
lineHeight: '19px'
32
33
};
34
35
const bodyStyle = {
36
padding: '0 0 0 24px'
37
};
38
39
const Tree = ({node}) => {
40
const [expanded, setExpanded] = React.useState(false);
41
const handleExpanderClick = () => setExpanded(!expanded);
42
return (
43
<div style={nodeStyle}>
44
<div style={headStyle} onClick={handleExpanderClick}>
45
<div style={wrapperStyle}>
46
{node.children && (<div style={expanderStyle}>{expanded ? '-' : '+'}</div>)}
47
</div>
48
<div style={nameStyle}>{node.name}</div>
49
</div>
50
{expanded && (
51
<div style={bodyStyle}>
52
{node.children?.map(node => <Tree key={node.name} node={node} />)}
53
</div>
54
)}
55
</div>
56
);
57
};
58
59
60
// Usage example:
61
62
const node = {
63
name: 'Dirask',
64
children: [
65
{
66
name: 'Wiki for Code',
67
children: [
68
{name: 'Posts'},
69
{name: 'Users'}
70
]
71
},
72
{name: 'Questions'},
73
{name: 'Finding & News'},
74
]
75
};
76
77
const App = () => {
78
return (
79
<div>
80
<Tree node={node} />
81
</div>
82
);
83
};
84
85
const root = document.querySelector('#root');
86
ReactDOM.render(<App />, root);