Languages
[Edit]
EN

React - simple tree component

7 points
Created by:
christa
300

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

Simple custom expandable tree component in React.
Simple custom expandable tree component in React.

Practical example:

// ONLINE-RUNNER:browser;

// import React from 'react';
// import ReactDOM from 'react-dom';

const nodeStyle = {
  	padding: '4px 0',
	fontFamily: 'system-ui',
  	fontSize: '13px'
};

const headStyle = {
	display: 'flex',
  	cursor: 'pointer'
};

const wrapperStyle = {
  	width: '20px',
};

const expanderStyle = {
	border: '1px solid #ebb2b2',
    borderRadius: '2px',
    width: '15px',
    height: '15px',
    textAlign: 'center',
    lineHeight: '14px',
    background: '#ffff8a'
};

const nameStyle = {
  	margin: '0 0 0 6px'

};

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);

 

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join