Home > Blockchain >  How to prevent mui datatables render when set states in onRowSelectionChange
How to prevent mui datatables render when set states in onRowSelectionChange

Time:08-30

I'm currently working on React js project with "mui-datatables": "^4.2.2".

I have a list of data divided on pages with the possibility of selecting an item through a checkbox :

enter image description here

My problem :

when I select an item in the second page, the component rerender and automatically back to the first page.

I think the problem is a set state inside onRowSelectionChange :

  const options = {
    filter: false,
    onRowClick: (rowData, rowMeta) => {
      console.log("--rowData --");
      console.log(rowData);
      console.log("--rowMeta --");
      console.log(rowMeta);
    },
    onRowSelectionChange: (
      currentRowsSelected,
      allRowsSelected,
      rowsSelected
    ) => {
      let items = [];
      allRowsSelected.forEach((row) => {
        items.push(data[row.dataIndex]);
      });
      setSelectedRows(items);
    },

How can i fix this problem ?

CodePudding user response:

you should store page number in the state as well say for example curPage:1 when page change you should update the curPage as well,now you can use this inside the options props you pass to mui-datatable.like this

const options = {
page:this.state.curPage,//incase its class component
onChangePage:(page)=>{
 this.setState({curPage:page});//assuming its a class component
},
filter: false,
onRowClick: (rowData, rowMeta) => {
  console.log("--rowData --");
  console.log(rowData);
  console.log("--rowMeta --");
  console.log(rowMeta);
},
onRowSelectionChange: (
  currentRowsSelected,
  allRowsSelected,
  rowsSelected
) => {
  let items = [];
  allRowsSelected.forEach((row) => {
    items.push(data[row.dataIndex]);
  });
  setSelectedRows(items);
},

hope this will help

  • Related