Checkbox state gets empty after page change

I have an array of objects that looks like this:

 const columns = [
    {
      key: "Source_campname",
      title: "TS Camp Name",
      customElement: function (row) {
        return (
          <FormControlLabel
            control={
              <Checkbox
                checked={checkbox[row.id]}
                key={row.id}
                onChange={() =>
                  handleChange(row.Source_campname, row.id, checkbox)
                }
                name={row.id}
              />
            }
            label={[row.Source_campname]}
          />
        );
      }
    },
    {
      key: "Tracker_campname",
      title: "TR Camp Name"
    }
  ];

You can see a "handleChange" function above, this is used to check/uncheck the component
The handleChange function looks like this:

const handleChange = (name, campid) => {
    setCheckBox({ ...checkbox, [campid]: !checkbox[campid] });
  };

You can also see a "customElement" function above. This function is rendered in another React component named ThanosTable. I will just write down part of the code where the rendering of customElement happens below.

return (
   <> columnArray[0].customElement(row) </>
);

In the end you get 10 checkboxes, and you have a few pages that can be changed using pagination.

Do check my codesandbox link here for a working example:
https://codesandbox.io/s/magical-germain-8tclq

Now I have two problems:

Problem 1) If I select a few checkboxes, then go to second page and return, the checkbox state is empty and the original checkboxes are unselected. No idea why that is happening. How do I prevent that?

Problem 2) The value of checkbox state is always an empty object ({}) inside customElement function. You can see this by checking console.log(checkbox) inside customElement function (Check Line 76 in codesandbox). I thought it should be an array with selected checkbox items.

8 thoughts on “Checkbox state gets empty after page change”

Leave a Comment