renakre
renakre

Reputation: 8291

React checkbox get (un)checked after the second click

Below is the part of the react component where a dynamic checkbox is listed:

   <div className="pb-4">
       <p>Choose the task owner(s):</p>
       {
           peerIds.map(id => {
               if (currentUserId != id)
                   return (
                       <label className="checkbox-inline mr-3">
                           <input onChange={onChange_TaskOwner}
                               type="checkbox"
                               name="taskowner"
                               checked={st_taskOwnersId.filter(function (item) {return (item == id)}).length > 0}
                               value={peers[id].id} />
                           <span>{peers[id].fullName}</span>
                       </label>

                   )
           })
       }
       <div style={{ clear: 'both' }}></div>
   </div>

In the above code I set checked to false/true if the current id is already in the hook state object called st_taskOwnersId.

I store the Ids of the checked items using hook as below. onChange_TaskOwner function updates the st_taskOwnersId depending on whether it is checked or unchecked:

const [st_taskOwnersId, set_taskOwnersId] = useState([] as any);

const onChange_TaskOwner = (event) => {
    event.preventDefault();
    if (event.target.checked)
        set_taskOwnersId([...st_taskOwnersId, event.target.value]);
    else
        set_taskOwnersId(st_taskOwnersId.filter(function (item) {
            return (item != event.target.value);
        }));
}

The code runs without errors. The only problem is I have to click twice to check/uncheck the check boxes. I have no clue why this is happening. Any help?

Upvotes: 6

Views: 5046

Answers (1)

aquilesb
aquilesb

Reputation: 2272

I believe the problem is on onChange_TaskOwner function. You should remove event.preventDefault(); call.

I tried to reproduce your component on this codepen, without the event.preventDefault(); works fine, if you add it, the same kind of error start happening.

Upvotes: 11

Related Questions