Abdulla Osama
Abdulla Osama

Reputation: 179

React Material UI Data Grid onSelectionModelChange with custome pagination

I am having a trouble using DataGrid onSelectionModelChange prop . I can get the current selected rows for a single page, but when I use custom pagination and move to the next page and use onSelectionModelChange again, I lose the previuos selections.

function DataTable(props, list, count) {

  const [page, setPage] = React.useState(1)
  const [selectionModel, setSelectionModel] = React.useState([]);
  const prevSelectionModel = React.useRef(selectionModel);


  let history = useHistory();
  const columns = [#cols here]

  React.useEffect(() => {

    listView(page, newSearch);
   
  }, [page, newSearch]);

  const data = {
    columns: columns,
    rows: JSON.parse(localStorage.getItem("results"))
  }

  return (
    <div style={{ height: 600, width: '100%' }}>
      <DataGrid
        autoHeight
        rows={data.rows}
        columns={columns}
        hideFooterPagination={true}
        checkboxSelection
        onSelectionModelChange={(ids) => {
          setSelectionModel(ids);
          console.log(selectionModel)
        }}
        pageSize={10}
        rowsPerPageOptions={[10]}
        // {...data}
      />
      <AppPagination
      setPage={setPage}
      page={page}
      />
    </div>
  );
}


enter code here

Upvotes: 4

Views: 10307

Answers (3)

Raushan Jha
Raushan Jha

Reputation: 139

Use Props keepNonExistentRowsSelected in DataGrid . If keepNonExistentRowsSelected props is true , then the selection model will retain selected rows that do not exist. Useful when using server side pagination and row selections need to be retained when changing pages.

 <StyledDataGrid
          keepNonExistentRowsSelected/>.

Usage with server-side pagination

Upvotes: 0

itiisennsinn
itiisennsinn

Reputation: 31

The props keepNonExistentRowsSelected works for your code. More information to see Mui data-grid docs and github issue

Upvotes: 3

Ahmed fouad
Ahmed fouad

Reputation: 109

This is a working example for your case : you can watch the console in this sandbox ... not losing selected rows

Live Demo

Edit 66424752/get-row-item-on-checkbox-selection-in-react-material-ui-data-grid

Upvotes: 0

Related Questions