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:
// ONLINE-RUNNER:browser;
// import React from 'react';
// import ReactDOM from 'react-dom';
const nodeStyle = {
padding: '4px 0',
fontFamily: 'Arial',
fontSize: '13px'
};
const headStyle = {
display: 'flex',
cursor: 'pointer'
};
const wrapperStyle = {
width: '20px',
};
const expanderStyle = {
border: '1px solid #ebb2b2',
borderRadius: '2px',
background: '#ffff8a',
width: '15px',
height: '15px',
textAlign: 'center',
lineHeight: '15px'
};
const nameStyle = {
margin: '0 0 0 6px',
lineHeight: '19px'
};
const bodyStyle = {
padding: '0 0 0 24px'
};
const Tree = ({node}) => {
const [expanded, setExpanded] = React.useState(false);
const handleExpanderClick = () => setExpanded(!expanded);
return (
<div style={nodeStyle}>
<div style={headStyle} onClick={handleExpanderClick}>
<div style={wrapperStyle}>
{node.children && (<div style={expanderStyle}>{expanded ? '-' : '+'}</div>)}
</div>
<div style={nameStyle}>{node.name}</div>
</div>
{expanded && (
<div style={bodyStyle}>
{node.children?.map(node => <Tree key={node.name} node={node} />)}
</div>
)}
</div>
);
};
// Usage example:
const node = {
name: 'Dirask',
children: [
{
name: 'Wiki for Code',
children: [
{name: 'Posts'},
{name: 'Users'}
]
},
{name: 'Questions'},
{name: 'Finding & News'},
]
};
const App = () => {
return (
<div>
<Tree node={node} />
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);