Material-table: How to change selected rows from outside of component?

Created on 12 Jun 2020  路  5Comments  路  Source: mbrn/material-table

I'm unable to find anything in the documentation about how to do this, I imagine it's using the tableRef property but I don't know what properties that contains that would be able to change the selected rows. I am using a table with selection enabled, basically I want somewhere outside of this component to handle the selected rows as well (like remove certain rows).

<MaterialTable
    columns={columns}
    data={files}
    title="Table"
    tableRef={tableRef}
    options={{
      selection: true,
    }}
>

const removeSelectedRow = (idx: number) => {
// what goes here?
tableRef.current.removeSelectedRow(idx);
}
question wontfix

Most helpful comment

I don't get why this feature hasn't been implemented yet. Programmatically selected rows is a common use case, i.e. when table being used in forms.

All 5 comments

I need this so bad!

I think I figured out how to solve it using tableRef, although it's not great:

const tableRef = useRef<any>(); // not sure if there's a better type for this

const removeFromChecked = (idx: number) => {
    if (!tableRef) {
      return;
    }

    tableRef.current.dataManager.changeRowSelected(false, [idx]);
};

return <MaterialTable
  tableRef={tableRef}
  data={data}
  columns={columns}
/>;

This seems like a common enough use case to be in the docs, I think.

I don't get why this feature hasn't been implemented yet. Programmatically selected rows is a common use case, i.e. when table being used in forms.

Trying to use the reverse of this by taking in URL query params and initially selecting a row based on the params. Tried using the tableRef technique shown by @Buuntu, but doing that makes it so you can't deselect the row from the table. This would be a good feature to add.

Edit: Looking at my code more, I think my problem actually had to do with the useEffect hook I was using. The conditional I had created to select an item made it so deselecting all items would run the hook again and thus take the params from the URL to select the item again.

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. You can reopen it if it required.

Was this page helpful?
0 / 5 - 0 ratings