I need help im using material-table on react for my data table. I want to use the selection and pagination at the same time, but the problem is if i select a certain row and change the page and return to previous page. it doesn't select that row. here is a sample snippet i created. Is it possible to override the selection props?
const Table = () => {
const [selectedRows, setSelectedRows] = useState([]);
function handleSelectChange(rows) {
setSelectedRows(rows)
}
return (
<MaterialTable
title="Remote Data Preview"
columns={[
{
title: 'Avatar',
field: 'avatar',
render: rowData => (
<img
style={{ height: 36, borderRadius: '50%' }}
src={rowData.avatar}
/>
),
},
{ title: 'Id', field: 'id' },
{ title: 'First Name', field: 'first_name' },
{ title: 'Last Name', field: 'last_name' },
]}
options={{
selection:true,
}}
onSelectionChange={(rows) => handleSelectChange(rows)}
data={query =>
new Promise((resolve, reject) => {
let url = 'https://reqres.in/api/users?'
url += 'per_page=' + query.pageSize
url += '&page=' + (query.page + 1)
fetch(url)
.then(response => response.json())
.then(result => {
resolve({
data: result.data,
page: result.page - 1,
totalCount: result.total,
})
})
})
}
/>
)
}
i already created an issue will put this a reference. https://github.com/mbrn/material-table/issues/1189
Since you already know the selected rows, you just have to modify your fetched data like this:
data: result.data.map(row => selectedRows.find(selected => selected.id === row.id) ? { ...row, tableData: { checked: true } } : row)
This will add the tableData.checked key to the fetched data and it will display it as selected.
Here is a codesandbox.