reactjsnext.js13tanstack

How to set default filter in tanstack table v8


The following is my tanstack table in react

const table = useReactTable({
        data,
        columns,
        getCoreRowModel: getCoreRowModel(),
        getPaginationRowModel: getPaginationRowModel(),
        onSortingChange: setSorting,
        getSortedRowModel: getSortedRowModel(),
        onColumnVisibilityChange: setColumnVisibility,
        onColumnFiltersChange: setColumnFilters,
        getFilteredRowModel: getFilteredRowModel(),
        filterFromLeafRows: false,
        getFacetedRowModel: getFacetedRowModel(),
        getFacetedUniqueValues: getFacetedUniqueValues(),
        state: {
            sorting,
            columnFilters,
            columnVisibility,
        },
        initialState: {
            pagination: {
                pageSize: 8,
            },
            columnFilters: [
                {
                    id: 'owner',
                    value: 'Alice',
                }
            ]
        }
    });

As you can see, I have added the column filter in the initial state, but that seems to have no effect.

I aim to filter the column owner, with the default value Alice.


Solution

  • You should add columnFilters to the state key as well.

    For eaxmple:

     const table = useReactTable({
        data,
        columns,
        state: {
          columnFilters: [
                {
                    id: 'owner',
                    value: 'Alice',
                }
            ]
        },
        ...