dimanche 20 juin 2021

handling multiple checkboxs and push or filter values based on selection

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>
))}



Aucun commentaire:

Enregistrer un commentaire