1

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?

1 Answer 1

1

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        
      })
    }
  }
...
Sign up to request clarification or add additional context in comments.

3 Comments

Nope, it is not working it gives an error like this: Expected an assignment or function call and instead saw an expression
Sorry, needed some time to write it better and to correct it, try now, it's harder without a whole working code! I hope it will work now, see for the filter only to adjust it if needed!
Thank you for the answer it is working but it has syntax error. There is no need of curly braces after the two arrows and there is no need to declare a variable returnValue. This is working onChange={(e) => setSelectedPackage((c) => e.target.checked ? [...c, item._id] : c.filter((el) => el !== item._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.