'Retain renderCell state after paginating data in DataGrid

Material UI DataGrid Pagination is resetting the values/states of the renderCell componenet.

For example in the following demo, whenever I turn a switch on and move to the second page, that switch resets to initial value when I come back to that page. any idea how to solve this issue ?

https://codesandbox.io/s/datagriddemo-material-demo-forked-ygrpw6?file=/demo.tsx



Solution 1:[1]

In simpler terms, you need to set the state in the outer component where the data table is being rendered. You can then pass the prop of each switch to the controlled switch.

In the outer component DataGridDemo(), the state will be an object of all the rows which are checked.

Your renderCell function will be like:

renderCell: (e) => <ControlledSwitch checked={checked} setChecked={prev => ({...prev, x: true})} /> where x signifies the Id of the row that you can fetch from the renderCell prop (e)

And your ControlledSwitch function will be like:

export default function ControlledSwitch({checked, setChecked}) {
  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setChecked(event.target.checked);
  };

  return (
    <Switch
      checked={checked}
      onChange={handleChange}
      inputProps={{ "aria-label": "controlled" }}
    />
  );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Winter