DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Tree In React

import React, {useState} from 'react'
import ReactDOM from 'react-dom'

function App() {
  const data = [
    {
      name: 'Node-1',
      id: 1,
      parent_id: null,
    },
    {
      name: 'Node-2',
      id: 2,
      parent_id: null,
    },
    {
      name: 'Node-1-1',
      id: 3,
      parent_id: 1,
    },
    {
      name: 'Node-1-2',
      id: 4,
      parent_id: 1,
    },
    {
      name: 'Node-1-1-1',
      id: 5,
      parent_id: 3,
    },
    {
      name: 'Node-1-1-2',
      id: 6,
      parent_id: 3,
    },
    {
      name: 'Node-1-2-1',
      id: 7,
      parent_id: 4,
    },
    {
      name: 'Node-2-1',
      id: 8,
      parent_id: 2,
    },
    {
      name: 'Node-2-2',
      id: 9,
      parent_id: 2,
    },
  ]
  // dependency

  return <Tree data={data} />
}

const TreeNode = ({node, data, onToggle}) => {
  const hasData = data.some((item) => item.parent_id === node.id)

  return (
    <div>
      <div onClick={() => onToggle(node.id)}>
        {hasData && <span>{node.isExpanded ? ' - ' : ' + '}</span>}
        {node.name}
      </div>
      {node.isExpanded ? (
        <div>
          {data
            .filter((item) => item.parent_id === node.id)
            .map((eachChild) => (
              <TreeNode
                key={eachChild.id}
                node={eachChild}
                data={data}
                onToggle={onToggle}
              />
            ))}
        </div>
      ) : (
        <></>
      )}
    </div>
  )
}

const Tree = ({data}) => {
  const [treeData, setTreeData] = useState(data)

  const handleToggle = (id) => {
    setTreeData((prevData) =>
      prevData.map((each) =>
        each.id === id ? {...each, isExpanded: !each.isExpanded} : each,
      ),
    )
  }

  return (
    <div>
      {treeData
        ?.filter((eachData) => eachData.parent_id === null)
        .map((eachNode) => (
          <TreeNode
            key={eachNode.id}
            node={eachNode}
            data={treeData}
            onToggle={handleToggle}
          />
        ))}
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))

Enter fullscreen mode Exit fullscreen mode

Top comments (0)