Himanshu Tariyal
Himanshu Tariyal

Reputation: 344

Material Ui data grid checkbox reset

I am working on a React Js project where I have different tabs and each tab has a different data grid table. All rows have check-boxes.

Problem : When I select any row from table 1 and switch to tab 2 and back to 1, the checkboxes disappear. I want them to be there so the users can see their selections. I defined separate components for them but still can't get the desired behaviour. This problem is only with the checkboxes, I tried consoling some state variables, and they were fine.

Live link : https://codesandbox.io/s/datagrid-reset-yhtt7?file=/src/App.js

Thank you in advance.

Upvotes: 0

Views: 4458

Answers (1)

Junhong Lim
Junhong Lim

Reputation: 36

From your given link, I updated @material-ui/data-grid package from 4.0.0-alpha.19 to 4.0.0-alpha.20 and modified the TabPanel component to use the DataGrid's onSelectionModelChange and selectionModel props:

function TabPanel(props) {
  const { children, value, index, rows, columns, ...other } = props;
  const [selectionModel, setSelectionModel] = useState([]); //added line
  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <div className={styles.table}>
          <DataGrid
            rows={rows}
            columns={columns}
            hideFooter
            checkboxSelection
            onSelectionModelChange={(newSelection) => {
              setSelectionModel(newSelection.selectionModel);
            }} //added line
            selectionModel={selectionModel} //added line
            disableSelectionOnClick={true}
          />
        </div>
      )}
    </div>
  );
}

Refer to Controlled selection section

Upvotes: 2

Related Questions