Search code examples
reactjsreact-tablereact-table-v7

How to render header row without cell and expand subrow react-table


Im using react-table v7. I have design like this. But i dont know how to custom row without cell and it still able to expand. Please tell me how to do it. Thank you so much. enter image description here


Solution

  • I found the solution. Use customTableCell and pass it to useTable, and then you can inject css to it, even you can hide or display value

    customTableCell component:

      const customTableCell = ({
        cell, column,
        cell: { value },
        column: { isError },
      }) => {
        const isSubRow = cell?.row?.depth !== 0
        const isShowHeader = column?.showHeaderExpand
        const isShowValue = (isShowHeader || isSubRow)
        return (
          <div className='cursor-pointer text-left' onClick={() => isSubRow && alert(value)}>
            {value == undefined ? (
              <span className="error">N/A</span>
            ) : (
              <span
                className={[isError && isError(value) ? "error" : "", isShowValue ? 'cell-with-value' : 'cell-no-value']
                  .join(" ")
                  .trim()}
              >
                {isShowValue && value}
                {isShowHeader && !isSubRow && <Tag> {cell?.row?.subRows?.length}</Tag>}
              </span>
            )}
          </div>
        );
      };
    

    your table:

     const defaultColumn = useMemo(
        () => ({
          Filter: DefaultColumnFilter,
          Cell: customTableCell || TableCell,   // <= this line
          Header: DefaultHeader,
        }),
        []
      );
    
      const instance = useTable(
        {
          columns,
          data: data || [zeroStateData],
          defaultColumn,                     // <= this line
          disableMultiSort: true,
          initialState: {
            pageIndex: paginationOptionState?.page - 1 || 0,
            pageSize: paginationOptionState?.pageSize || 25,
            hiddenColumns: columns.filter(column => !column?.isVisible).map(column => column.accessor),
            sortBy: columns.filter(column => typeof column?.isSortedDesc === 'boolean').map(column => ({ id: column.accessor, desc: column?.isSortedDesc })),
          },
          ...optionsUseTable
        },
        ...hooks
      );