reactjstypescriptreact-table

React-Table v7 Columns Typscript style type problem


hello i'm stuck and it would be nice if you could tell me about the problem:

I implemented react-table with these columns

enter image description here

and as usual rendering them then I wanted to make sure that each column gets dynamic styles and nothing came to my mind how to simply declare the style property inside each column.

As a result, after looking in different places, I got stuck at this moment

enter image description here

typescript error sounds like this:

TS2322: Type '{ Header: string; accessor: "address"; style: { flex: string; minWidth: string; }; }' is not assignable to type 'Column'.   Object literal may only specify known properties, and 'style' does not exist in type 'ColumnInterface & { accessor: "address"; } & ColumnInterfaceBasedOnValue<IExtendedColumnInterface, string>'.

I'm new to typescript and can't figure out where I'm making a mistake I would appreciate any hint or help thanks


Solution

  • You could extend the column definition type to suit your needs. Use the ColumnDef type of tanstack/react-table and add your style object.

    import type { ColumnDef } from '@tanstack/react-table';
    
    // New custom column def type
    export type ColumnDefType<T> = ColumnDef<T> & { style?: Record<string, string> };
    

    You could use that type when typing your columns. So the style object is available when you create your rows for example. The style object can be extracted from column.columnDef and applied where necessary.

    import type { ColumnDefType } from '<custom-type-file-location>';
    
    const columns = useMemo<ColumnDefType<YourRowType>[]>(
        () => [
          {
            header: 'Name',
            accessorKey: 'name',
            style: ...
          }
        ]
    )
    

    This example uses @tanstack/react-table v8