Home > front end >  Push objectIds in an array when checkbox is checked in a React.js Functional Component
Push objectIds in an array when checkbox is checked in a React.js Functional Component

Time:09-26

I have an array in which I want to push the objectIds whenever the checkbox is checked and remove the ids after admin removes the check-mark from it.

<Form.Label>Select Package/s:</Form.Label>
{packages.map((item) => (
  <Form.Check
    key={item._id}
    type="checkbox"
    label={item.name}
  />
))}

This is the respnse: enter image description here

How can I do that?

CodePudding user response:

try to set onChange eventhandler on each list item, and spread the checked packages state:

const [checkedPackages, setCheckedPackages] = useState([]);

... 

<Form.Check
  key={item._id}
  onChange={
    (e) => {
    setCheckedPackages((c) => {
       let returnValue = e.target.checked ? 
         [...c, item._id] 
         :
         c.filter(el => el != item._id);
       return returnValue        
      })
    }
  }
...
  • Related