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.

1 thought on “Checkbox state gets empty after page change”

  1. enter image description here

    The useEffect hook embodies all the lifecycle events of a component. Therefore if you try to set checkbox in useEffect it’ll infinitely update the component because updating state calls useEffect. This is probably why you see your state constantly being reset.

    Instead, initialize your state with the rows before rendering.

    const rows = [
      ...
    ];
      
    let checkboxObj = {};
    
    // if (rows) {
    rows.forEach((e) => {
      checkboxObj[e.id] = false;
    });
    const [checkbox, setCheckBox] = useState(checkboxObj);
    
    Reply

Leave a Comment