Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

82
Views
Handle checkboxes with useState object

I have some checkboxes displayed using .map() function which is retrieving the data from a JSON file.

What i have achieved so far, is to store the clicked checkbox into the state (which is an object). But after I click another checkbox, it removes the previous one and store the latest..

I basically want to store all the checked ones, and if you remove them to remove it from the state.

Here's my handleCheck() function:

const handleCheckInput = (
      e: React.ChangeEvent<HTMLInputElement>,
      key: number,
      questionId: number,
   ) => {
      let newTickArray = [...tick];
      newTickArray[key] = !tick[key];
      setTick(newTickArray);
      setValues({ ...values, [questionId]: e.target.value });
   };

Any help will be appreciated

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Update:

Changed [questionId]: e.target.checked to [questionId]: e.target.value.

Answer:

Here is how you do it (I used ellipsis ... for parts that don't need to be changed and also for brevity):

(Also remember to use e.target.checked - the right property for checkbox elements - instead of e.target.value).

const handleCheckInput = (
  e: React.ChangeEvent<HTMLInputElement>,
  key: number,
  questionId: number) => {
    ... 

    if (e.target.checked) {
        setValues({ ...values, [questionId]: e.target.value});
    } else {
        // Remove unchecked from state.
        let { [questionId]: deletedKey, ...restOfObj } = values;
        setValues(restOfObj);
    }
}; 
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!