sk soyeb
sk soyeb

Reputation: 1

defaultChecked checkbox onChange event not running on first click (react.js)

This is the react jsx code that I have inside a component,

{selectedGrpList.includes(item.id.toString()) ? (
  <input
    type='checkbox'
    onChange={(e) => {
      handleGrpItemClick(item.id)
    }}
    defaultChecked={true}
  />
) : (
  <input
    type='checkbox'
    onChange={(e) => {
      handleGrpItemClick(item.id)
    }}
  />
)}

when onChange event occurs handleGrpItemClick function should run. This is the code inside handleGrpItemClick function

function handleGrpItemClick(id) {
    const list = selectedGrpList
    if (list.includes(id.toString())) {
      list.splice(list.indexOf(id.toString()), 1)
    } else {
      list.push(id.toString())
    }
    setSelectedGrpList(list)
}

But the problem is when the defaultChecked input element is clicked for the first time the checkbox becomes unchecked but the onChange doesn't run.

I don't know why is this happening.

I tried by replacing onChange with onClick but still it isn't running when defaultChecked input element gets clicked for the first time.

Upvotes: 0

Views: 54

Answers (1)

Unmitigated
Unmitigated

Reputation: 89234

You should not mutate the state directly. Instead, make a copy to set as the new state. See Updating Arrays in State.

Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in state. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array.

function handleGrpItemClick(id) {
    id += '';
    setSelectedGrpList(selectedGrpList.includes(id) ? 
        selectedGrpList.filter(x => x !== id) :
        [...selectedGrpList, id]);
}

Upvotes: 0

Related Questions