skip to Main Content

I am using React Table v8 for my new web app. I have a table built with checkboxes for selecting rows. In a component up higher in the component tree I am doing something with the selected rows, and then I want to clear all the selected rows. I found the function toggleAllRowsSelected while searching. And I tried adding this ‘useEffect’ in to my table component.

useEffect(() => {
    if (selectedRows.length === 0) {
        table.toggleAllRowsSelected(false);
    }
}, [selectedRows]);

And then I passed down ‘selectedRows’ from my component up higher in the component tree.
But that caused a continuous running loop.

I am creating my ReactTable like this:

const table = useReactTable({
    data,
    columns,
    state: {
        sorting,
        rowSelection,
        globalFilter,
        columnFilters
    },
    onSortingChange: setSorting,
    onRowSelectionChange: setRowSelection,
    onColumnFiltersChange: setColumnFilters,
    onGlobalFilterChange: setGlobalFilter,
    enableRowSelection: true,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel()
    // debugTable: true
});

Anyone know how I can properly achieve this?

Basically I just want to pass down a signal/trigger to deselect all rows in the table from a component above the table itself.

2

Answers


  1. Just from this code snipped I cant tell why you have a render loop.

    But it seems that you have 2 components which both keep track of the RowSelectionState:

    • The higher component tracks "selectedRows"
    • The lower component tracks "rowSelection"

    This seems problematic. A state should have a single source of truth.

    • Perhaps you could eliminate "selectedRows" and pass down "rowSelection" and "setRowSelection"
    • Use a context to make "rowSelection" and "setRowSelection" available to the react table component
    • store the rowSelection state outside of react by using something like "Jotai"

    If the render loop disappears when "strict mode" is turned off, then a useEffect is causing the issue.
    Otherwise I would suspect the way you are setting "selectedRows" and "rowSelection" is bugged

    Login or Signup to reply.
  2. I have implemented a table with a button to deselect all rows.
    I have used ref and then forwardRef to send the needed methods.

     useImperativeHandle(ref, () => ({
        resetSelectedRows: () => toggleAllRowsSelected(false)
      }));
    ...
    //In the parent
    tableRef.current?.resetSelectedRows();
    

    Edit goofy-cherry-vwjm3c

    So, I think using this approach can solve the issue you presented

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search