Bert Van Hecke
Bert Van Hecke

Reputation: 278

Shadcn reusable Data Table component with expandable subrows in Typescript

I use the reusable data table component from ShadcnUI in my project. Now i want to make the rows expandable. I just can't get it to work with the expandable API from Tanstack-Table. Typescript gives me an error saying my row (which is of type TData) does not have a property 'subrows'. I understand that TData is a generic type and so this error is correct but how would i go about making the expandable row functionality generic?

The error: Property 'subRows' does not exist on type 'TData'.

Parent component

export function ParentTable({ searchParams }: IndexPageProps) {
  const queryClient = useQueryClient();

  const { data, isLoading, error } = useQuery({
    queryKey: ["key", searchParams],
    queryFn: async () => await fetchSomeData(searchParams),
  });


  const columns = React.useMemo<ColumnDef<SomeType>[]>(
    () => [//left out for simplicity],
    []
  );

  return (
    <DataTable
      columns={columns}
      data={data.data}
      pageCount={data.pageCount}
    />
  );
}

Reusable data table

interface DataTableProps<TData, TValue> {
  columns: ColumnDef<TData, TValue>[];
  data: TData[];
  pageCount?: number;
}

export function DataTable<TData, TValue>({
  columns,
  data,
  pageCount,
}: DataTableProps<TData, TValue>) {

  //Other functionalities left out for simplcity

  const table = useReactTable({
    data,
    columns,
    pageCount: pageCount ?? -1,
    state: {
      pagination,
      sorting,
      columnVisibility,
      rowSelection,
      columnFilters,
      globalFilter,
      expanded
    },
    enableRowSelection: true,
    onRowSelectionChange: setRowSelection,
    onPaginationChange: setPagination,
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    onGlobalFilterChange: setGlobalFilter,
    onColumnVisibilityChange: setColumnVisibility,
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFacetedRowModel: getFacetedRowModel(),
    getFacetedUniqueValues: getFacetedUniqueValues(),
    onExpandedChange: setExpanded,
    getExpandedRowModel: getExpandedRowModel(),
    getSubRows: row => row.subRows, //here is the typescript error
    manualPagination: true,
    manualSorting: true,
    manualFiltering: true,
    meta: {
      updateData: (rowIndex: number, columnId: number, value: string) => {
        setTableData((prev) =>
          prev.map((row, index) =>
            index === rowIndex ? { ...prev[rowIndex], [columnId]: value } : row
          )
        );
      },
    },
  });

  return (
    //Table component left out for simplicity
  );
}

I'd really appreciate any help! Thanks.

Upvotes: 0

Views: 48

Answers (0)

Related Questions