1

how to handle checkbox is selected or not and push the object if selected and remove if unselected?

this is the initial arr set to state

let arr=[{lable:lable1,value:value1}
{lable:lable2,value:value2}
{lable:lable3,value:value3}
]

handle function triggered on selecting checkbox

  function handleChange(item) {
        let temp = [...arr];
     if (temp.includes(item.value)) {
       temp = temp.filter((value) => value != item.value);
     } else {
       temp.push(item.value);
     }
     setState(temp);
  }

multiple checkbox iterated based on array

      {arr.map((item, i) => {
        return (
             
                <label className="check-wrap">
                  <input
                    className="check-field"
                    checked={ ? } // how to handle checkbox is selected or not
                    name={item.lable}
                    onChange={() => handleChange(item)}
                    type="checkbox"
                  />
                  <span className="check-label">{item.value}</span>
                </label>
            </div>
))}

issue in codesandbox

1 Answer 1

1

You should use prevState instead of referencing the state value directly.

// ... rest of the onChange function
this.setState(prevState => ({
 arr: prevState.arr.includes(temp)
    ? prevState.arr.filter(value => value !== item.value)
    : [...prevState.arr, temp]
}))

You can read up on setState operations in here

Hooks works on the same principle:

const [arr, setArr] = useState([])

// ...later
setArr(prevArr => prevArr.includes(temp)
  ? prevArr.fitler(value => value !== item.value)
  : [...prevArr, temp]
)
Sign up to request clarification or add additional context in comments.

3 Comments

how to do in useState hooks ?
codesandbox.io/s/vigorous-moon-4inbh?file=/src/App.js can u please look into this code sandbox and see the issue in my code. Thanks in advance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.