in DataGrid of Material UI X We can select or deselect rows using keyboard shortcuts and mouse but how to select or deselect without them. rows should be selected or deselcted on conditions automatically like toggle rows selections with on some events or methods invokes or clicking on custom buttons or change in data of other components
function DataGridDemo() {
const { data, isLoading, error, refetch } = useQuery('docs', Docs.getAll);
const columns = useColumns();
const [rows, setRows] = React.useState([]);
useEffect(() => {
data && setRows(data);
}, [data]);
return (
<Box>
<DataGrid
disableRowSelectionOnClick
checkboxSelection
loading={isLoading || rows?.length === 0 }
rows={rows}
columns={columns}
/>
</Box>
);
}
export default DataGridDemo;
DataGrid component has two props for this:
rowSelectionModel
: This prop defines the currently selected row IDs. Pass your selectedRows state variable to it.
onRowSelectionModelChange
: This callback function is triggered whenever the selection changes. Use it to update your selectedRows state based on your custom logic:
So you just have to add ids of rows to rowSelectionModel which will automaticaly select the rows if you have selection check boxes then it will be checked automatically. and Similarly remove ids of rows which should be deselected.
import React, { useState, useEffect } from 'react';
import { DataGrid } from '@mui/x-data-grid'; // version ^7.15.0
import { Button, Box } from '@mui/material';
function DataGridDemo() {
const [rows, setRows] = useState([]);
const [selectedRows, setSelectedRows] = useState([]);
useEffect(() => {
const fetchedData = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' },
{ id: 3, name: 'Alice Johnson' },
{ id: 4, name: 'Bob Brown' }
];
setRows(fetchedData);
}, []);
const clearRowSelection = () => setSelectedRows([]);
const selectEvenRows = () => {
const evenRows = rows.filter(({id}) => (id) % 2 === 0).map(row => row.id);
setSelectedRows(evenRows);
};
const deselectEvenRows = () => {
const remainingRows = selectedRows.filter((id) => id % 2 !== 0);
console.log({remainingRows})
setSelectedRows(remainingRows);
};
return (
<Box>
{selectedRows+""}
<DataGrid
rows={rows}
columns={[{ field: 'id' }, { field: 'name' }]}
checkboxSelection
rowSelectionModel={selectedRows}
onRowSelectionModelChange={(newSelection) => setSelectedRows(newSelection)}
/>
<Button onClick={clearRowSelection}>Clear Selections</Button>
<Button onClick={selectEvenRows}>Select Even Rows</Button>
<Button onClick={deselectEvenRows}>Deselect Even Rows</Button>
</Box>
);
}
export default DataGridDemo;
You can use with your custom logics like:
useEffect(() => {
if (someCondition) {
setSelectedRows([rowId1, rowId2]); // Select specific rows
} else {
setSelectedRows([]);
}
}, [someCondition]);