Search code examples
reactjsmui-datatable

Selecting row(s) imperatively


Is there any way to set a row or multiple rows as checked imperatively in mui-datatables?

In the documentation the only thing I found even close was a setSelectedRows function passed to customToolbarSelect, but you can only access this function as a trigger after a row has already been manually selected.

I want the ability to write a function outside the datatable component that can change the "checked" state of a row. Particularly the ability to set all rows on a page as checked without setting every row in every page as checked. The built in "select all" functionality only performs the latter.


Solution

  • Looks like the answer is passing a state object to the rowsSelected prop like this:

    // selected rows is an array of indices
    const [selectedRows, setSelectedRows] = React.useState([3]);
    
    const options: MUIDataTableOptions = {
    ...
    rowsSelected: selectedRows, // on init, the 4th row will be checked
    ...
    }
    
    return (
    <>
      <Button onClick={() => setSelectedRows([1, 2, 3])}>Change!</Button>
      <MUIDataTable ... options={options} />
    </>
    )
    
    

    Clicking on the Change! button will set the 2nd, 3rd, and 4th, rows to checked and uncheck all the others.