I have two MUI datagrid side by side let say left grid a sending grid and right grid a receiving grid I have added checkbox selection to the sending grid and one button in the Grid toolbar. What I want is user will select a row using checkbox and click on assign row and that selected row will be added to the receiving grid.
Currently How I have done it. This is codesandbox link please check this out
I want know is this correct way to do it are there any other way where I can use MUI API. I have premium subscription so I can access all the API's. Is there any example.
My method
Created context which will be consumed by both sending grid and receiving grid and whenever user select row and click on assign button. context will be updated and it will save selected row data in that context. As receiving grid also consuming that context It will get re rendered and it will use stored data in context and append in its rows and this is how new row will be added.
- Select row using checkbox this will trigger
onRowSelectionModelChangeand on this callback I have retrieved selected row data using this method
const onRowsSelectionHandler = (ids) => {
const selectedRowsData = ids.map((id) => rows.find((row) => row.id === id));
setSelectedRows(selectedRowsData);
};
and set this data in state to use it later. on Assign button click I will store saved array data in context
const { updateArray } = useArrayContext();
function Assigntoolbar() {
const handleClick = () => {
updateArray(selectedRow);
};
return (
<GridToolbarContainer>
<Button
color="primary"
startIcon={<ArrowForwardIcon />}
onClick={handleClick}
>
Assingn Selected
</Button>
</GridToolbarContainer>
);
}
And in receiving grid I have updated row like this
export default function ReceivingGrid() {
const [rowsData, setRows] = React.useState(rows);
const { array } = useArrayContext();
React.useMemo(() => {
if (array.length > 0) {
setRows((prevRows) => [...prevRows, ...array]);
}
}, [array])
return (
<div style={{ height: 400, width: "100%" }}>
<DataGridPro
rows={rowsData}
columns={columns}
checkboxSelection
/>
</div>
);
}