dimanche 14 juillet 2019

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=></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?




Aucun commentaire:

Enregistrer un commentaire