material-table icon indicating copy to clipboard operation
material-table copied to clipboard

An action to clear selection

Open serotonyn opened this issue 7 years ago • 8 comments

Is there a way to clear current selection without having to click on the checkbox in the table header ? I mean by implementing a button.

serotonyn avatar Jan 12 '19 19:01 serotonyn

Hi @serotonyn ,

Unfortunately. It is controlled data by table.

mbrn avatar Jan 12 '19 19:01 mbrn

Thank you @mbrn for your reply. In this case, I'm thinking about forcing component to update.

serotonyn avatar Jan 12 '19 19:01 serotonyn

Yes ıt may work. Share result with us :)

mbrn avatar Jan 12 '19 22:01 mbrn

I think these two tickets might be related? Just dropping the link here for others researching: https://github.com/mbrn/material-table/issues/221

Jaketh avatar Feb 19 '20 15:02 Jaketh

You can pass in tableRef and using that set this tableRef.current.onAllSelected(false) which should clear active selection as well as selection header

yanamandra09 avatar Mar 31 '20 20:03 yanamandra09

how this can be done with Hooks?

gatz2 avatar Mar 01 '21 04:03 gatz2

@gatz2 I think this should explain how a hook is used, including example usage

import { useRef } from 'react'

...

const tableRef = useRef()

...

// Example usage
const clearSelection = () => {
  // Should check that the element is available to prevent errors
  if (tableRef.current) {
    tableRef.current.onAllSelected(false)
  }
}

...

<MaterialTable
  tableRef={tableRef}
  ...
/>

<button onClick={clearSelection}>Clear selection</button>

nilslp avatar May 18 '21 13:05 nilslp

A simple solution to this is:-

const Example = () => {
  const table = useMaterialReactTable({
    columns,
    data,

    <Button
      onClick={() => {
        // Get selected rows
        const selectedRows = table.getSelectedRowModel().rows;
       
       // Do some action

        // Clear selected rows
        table.resetRowSelection();
      }}
    >
      Click me
    </Button>
  });

  return <MaterialReactTable table={table} />;
};

shivamGhodke avatar May 09 '24 23:05 shivamGhodke