简体   繁体   中英

multi level table row expand collapse react

I have multi level array of object, so if key value is object, then add expand/collapse button, and on click of it, render rows and so on...

var cars = {
  label: 'Autos',
  subs: [
    {
      label: 'SUVs',
      subs: []
    },
    {
      label: 'Trucks',
      subs: [
        {
          label: '2 Wheel Drive',
          subs: []
        },
        {
          label: '4 Wheel Drive',
          subs: [
            {
              label: 'Ford',
              subs: []
            },
            {
              label: 'Chevrolet',
              subs: []
            }
          ]
        }
      ]
    },
    {
      label: 'Sedan',
      subs: []
    }
  ]
}

I created a demo for you using reactjs and recursion around your given object.

codesandbox-demo

Have a look at it, if it helps in your use case. you can refer the below code to infer more

import React from "react";

const cars = {
  label: "Autos",
  subs: [
    {
      label: "SUVs",
      subs: []
    },
    {
      label: "Trucks",
      subs: [
        {
          label: "2 Wheel Drive",
          subs: []
        },
        {
          label: "4 Wheel Drive",
          subs: [
            {
              label: "Ford",
              subs: []
            },
            {
              label: "Chevrolet",
              subs: []
            }
          ]
        }
      ]
    },
    {
      label: "Sedan",
      subs: []
    }
  ]
};

const generateRow = (rowData, open, setOpen) => {
  const handleExpand = () => {
    let set = new Set(open);
    set.add(rowData.label);
    setOpen(set);
  };

  const handleCollapse = () => {
    let set = new Set(open);
    set.delete(rowData.label);
    setOpen(set);
  };

  return (
    <div>
      <p>
        {rowData.label}
        &nbsp;
        {rowData.subs.length > 0 && !open.has(rowData.label) && (
          <button onClick={handleExpand}>&#x2193;</button>
        )}
        {rowData.subs.length > 0 && open.has(rowData.label) && (
          <button onClick={handleCollapse}>&#x2191;</button>
        )}
      </p>
      {rowData.subs.length > 0 && open.has(rowData.label) && (
        <ul>
          {rowData.subs.map((child) => {
            return (
              <li key={child.label}>{generateRow(child, open, setOpen)}</li>
            );
          })}
        </ul>
      )}
      <ol></ol>
    </div>
  );
};

const App = () => {
  // open state to keep trach of which labels are selected to be open or not
  // use recursion to generate list on demand

  const [open, setOpen] = React.useState(new Set());

  return generateRow(cars, open, setOpen);
};

export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM