简体   繁体   中英

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

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

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

Live Demo

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM