1

when I click in the checkbox of the table row, I am updating the array selecteddata with id and after that I am passing the checked value by finding whether id exists in the selecteddata to check the checkbox. I am able to store the id in selectedData but it is not showing instance changes in checkbox.

const [selectedData, setSeletcedData] = useState([]);

  const handleCheckboxSelect = (id) => {
    setHasSelectedAll(false);
    setSeletcedData((selectedData) => {
      if (selectedData.includes(id)) {
        return selectedData.filter((currentId) => id !== currentId);
      } else {
        selectedData.push(id);
        return selectedData;
      }
    });
  };



<CDataTable
          items={matter}
          fields={fields}
          hover
          pagination
            count: (item) => (
              <CFormGroup variant="checkbox" className="checkbox">
                <CInputCheckbox
                  id="checkbox1"
                  name="checkbox1"
                  value="option1"
                  checked={selectedData.includes(item.id)}
                  onChange={(e) => handleCheckboxSelect(item.id)}
                />
              </CFormGroup>
            ),
          }}
        />

2 Answers 2

1

You're returning the same array reference in the line

selectedData.push(id);
return selectedData;

which won't cause the component to re-render, you should return a new array with the new item with, using spread operator or Array Cloning

spread operator :

     return [...selectedData,id];

Cloning :

     const newArray = Array.from(selectedData);
     newArray.push(id);
     return newArray;
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, it worked, i am new to react so such issues are always bugging me
1

Use spread operator to return new Array instead push

else {
  return [...selectedData, id];
}

2 Comments

i think you are mean to spread selectedData not id
should be [...selectedData,id]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.