Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 914
renakre Avatar asked Jul 14 '19 13:07

renakre


1 Answers

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.

like image 77
aquilesb Avatar answered Sep 18 '22 14:09

aquilesb