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
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:
This seems problematic. A state should have a single source of truth.
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
I have implemented a table with a button to deselect all rows.
I have used ref and then forwardRef to send the needed methods.
So, I think using this approach can solve the issue you presented