React Table using hooks expand and collapse rows

Vivek V Nair picture Vivek V Nair · Mar 18, 2020 · Viewed 15.4k times · Source

I am using react-table component inside my project. The row expansion property is something that my features utilized and it is working fine now.

I need the ability to collapse all the rows while I expand a row. ie Only one row should be open at a time. I did go through many documentation and stackoverflow links but none didn't work out. Please note that this implementation is using hooks. Just like the one mentioned here : https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/expanding

By default they allow to open more than one row at a time, but I need to implement the opposite.

The closest I came to is this : Auto expandable rows and subrows react table using hooks

But here its opening on initial load.

Thanks

Answer

Niyas Nazar picture Niyas Nazar · Mar 18, 2020

I have only added a portion of App function here. Codesandbox: https://codesandbox.io/s/jolly-payne-dxs1d?fontsize=14&hidenavigation=1&theme=dark.

Note: I am not used to react-table library. This code is a sample that only works in the table with two levels of rows. You can optimize the code with recursion or some other way to make the code work in multi-level tables.

Cell: ({ row, rows, toggleRowExpanded }) =>
          // Use the row.canExpand and row.getToggleRowExpandedProps prop getter
          // to build the toggle for expanding a row
          row.canExpand ? (
            <span
              {...row.getToggleRowExpandedProps({
                style: {
                  // We can even use the row.depth property
                  // and paddingLeft to indicate the depth
                  // of the row
                  paddingLeft: `${row.depth * 2}rem`
                },
                onClick: () => {
                  const expandedRow = rows.find(row => row.isExpanded);

                  if (expandedRow) {
                    const isSubItemOfRow = Boolean(
                      expandedRow && row.id.split(".")[0] === expandedRow.id
                    );

                    if (isSubItemOfRow) {
                      const expandedSubItem = expandedRow.subRows.find(
                        subRow => subRow.isExpanded
                      );

                      if (expandedSubItem) {
                        const isClickedOnExpandedSubItem =
                          expandedSubItem.id === row.id;
                        if (!isClickedOnExpandedSubItem) {
                          toggleRowExpanded(expandedSubItem.id, false);
                        }
                      }
                    } else {
                      toggleRowExpanded(expandedRow.id, false);
                    }
                  }
                  row.toggleRowExpanded();
                }
              })}
            >
              {row.isExpanded ? "👇" : "👉"}
            </span>
          ) : null