onSelectionChange and setState not working well
Describe the bug
Checkboxes do not get selected when setState is used alongside onSelectionChange. Currently using version 1.32.0
To Reproduce Steps to reproduce the behavior:
- Create a table and set a
onSelectionChange() - do a
this.setState()with the data taken fromonSelectionChange - Checkboxes does not get checked
- Example:
<MaterialTable
columns={[...]}
data={...}
onSelectionChange={(data) => this.setState({ selectedOrders: data })}
options={{...}}
/>
Expected behavior Checkboxes to be checked and state is set.
Desktop (please complete the following information):
- OS: macOS
- Browser: Firefox, Google Chrome
- Version: Firefox Quantum Version 66.0.3 (64 bit), Google Chrome Version 73.0.3683.103 (64 bit)
Nevermind this issue, realized it was due to re-rendering of the component that made it not checked.
How did you solve this issue?I am calling a function inside onSelectionChange inside which i am changing state. I there another way?
Hey @uplsaurabhA, there is a way, which is to do it like this:
handleCheckboxClick = (rowData) => {
this.setState({
selectedItems: {
...rowData,
tableData: {
checked: true,
}
}
})
}
You can override the checkbox to be checked using material-table
It is a simple workaround and not logically correct but you have to set the logic toward it yourself. Just guiding in the right direction right now.
With latest version you can call functions of material-table with tableRef. Did you check it?
In case anybody still has trouble fixing this issue. You can either:
- Add shouldComponentUpdate check to force the material-table not to be re-rendered, or
- Change the data array which you feed into the material-table, please refer to #96 for detailed implementation
I am trying to change state after onSelectionChange , but after changing the state , selection on the table is not shown in the UI , field is selected but its not showing in the UI. Please help
as @DeanDiDi said, you should either cause the table to re-render (shouldComponentUpdate) or explicitly tell the row that it is selected - look at #96
Instead of using useState, another way is to use useRef. useRef will not cause a re-render so it's independent of the component lifecycle, and in this case will cause the checkboxes to function normally, a simple fix, hopefully this helps someone. Also note that in order to get the array, you have to access the .current property in useRef.
const selectedRow = React.useRef([]);
const handleClick = rows => {
selectedRow.current = rows;
console.log(selectedRow: , selectedRow.current);
};
//inside the material-table onSelectionChange={rows => { handleClick(rows); }}
Is it possible to select all rows on current page?
hi @Tellisense @mbrn , or other people who may help,
besides useRef, are there other ways to change the state of another object when onSelectionChange? I am facing an issue, which is whenever the table selection is changed, I want to toggle the disabled state of a button based on the selection. I have tried with useRef like below, but since the useRef does not trigger re-render, the button disabled style is not changed:
const confirmSelectionBtn = React.useRef();
const handleTableSelectionChange = (rows) => {
if (confirmSelectionBtn && confirmSelectionBtn.current) {
confirmSelectionBtn.current.disabled = rows.length === 0;
}
};
I think setState should be possible inside the onSelectionChange event, so I don't understand why material table does not support this. Or maybe I just missed how to make it happen?
And there is another issue I found out while solving this problem. If I:
- sort the table by a column, e.g. "birth year" column in my example,
- then select a row by checking the checkbox,
- then click on the Confirm button, which has nothing to do with the table, and I set a state inside the onClick event on the btn,
- then the table sorting and my selection are all gone / reset. but this only happens on the first time I load the page. If I repeat again without refresh, it works fine.
Should I report a new issue? But I suspect this has something with the onSelectionChange event. Here is my code:
const Overview = () => {
// @ts-ignore
const confirmSelectionBtn = React.useRef(null);
const [data, setData] = React.useState<boolean>(false);
const handleBtnClick = () => {
setData(true);
};
const handleTableSelection = (rows: any) => {
console.log(rows);
};
return (
<div>
<MaterialTable
icons={tableIcons}
title="Actions On Selected Rows Preview"
columns={[
{ title: 'Name', field: 'name' },
{ title: 'Surname', field: 'surname' },
{ title: 'Birth Year', field: 'birthYear', type: 'numeric' },
]}
data={[
{ name: 'Mehmet', surname: 'Baran', birthYear: 1987 },
{ name: 'Zerya Betül', surname: 'Baran', birthYear: 2017 },
]}
options={{
selection: true
}}
onSelectionChange={(rows) => handleTableSelection(rows)}
/>
<Button
ref={confirmSelectionBtn}
id="btn"
name="btn"
onClick={handleBtnClick}
size="small"
>
Confirm
</Button>
</div>
);
};
Another fix is to make sure the state update resulting from the onSelectionChange call updates the value provided to the data property passed into MaterialTable.
Here's a sample:
<MaterialTable
data={this.state.data}
onSelectionChange={(rows, rowsData) => {
const updatedData = data?.map((t) => {
if (t._id === rowData._id) {
return {
...t,
tableData: rowData.tableData,
};
} else {
return t;
}
});
this.setState({
data: updatedData,
selectedRows: rows,
});
})
/>
@xiaochenzhang This should resolve your issue
I was facing the same issue and found out the useState name must be the same as MRT_RowSelectionState, after I changed it, it works:
If you are facing this issue when you select the checkbox and the UI doesn't update write your state like this (it's the same name they use in the docs, but I think it's not helpful because they don't make it clear):
// the state must be written like this since
// MRT uses under the hood the state name to match the type MRT_RowSelectionState
const [rowSelection, setRowSelection] = useState<MRT_RowSelectionState>({});
Just for your reference and to show what I meant above MRT_RowSelectionState type is:
export interface RowSelectionTableState {
rowSelection: RowSelectionState;
}