Search code examples
react-tablereact-table-v7

How to create a row with one cell in a expandible react table?


I want to use useExpanded to create a subrow that stretches along all columns, similar to the screenshot. In the react table example it only provides expanded rows with the same columns like the table header.

enter image description here

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    state: { expanded }
  } = useTable(
    {
      columns: userColumns,
      data
    },
    useExpanded // Use the useExpanded plugin hook
  );

Solution

  • You need to set the html colspan attribute on the td element to the number of cells in the row.

    <tr>
     <td colspan="3">Extra: cdd</td>
    </tr>
    
    

    Here is a good starting point. See the CSB

    <tbody {...getTableBodyProps()}>
      {rows.map((row, i) => {
        prepareRow(row);
        return (
          <tr {...row.getRowProps()}>
            {!row.canExpand && <td colSpan={3}>{row.cells[1].value}</td>}
            {row.canExpand &&
              row.cells.map((cell) => {
                return (
                  <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                );
              })}
          </tr>
        );
      })}
    </tbody>