jeudi 5 octobre 2023

React multiple checkbox unchecking checkbox on button click

I am using checkboxes to filter array in react This is my code.

 const [selectedSubCats, setSelectedSubCats] = useState([]);
  const [subCategoryName,setSubCategoryName] = useState([])

{subCategories?.map((item, index) => (
              <div className="category-checkbox" key={index}>
                <CheckBoxButton
                  id={item.id}
                  name={item.name}
                  value={item.id}
                  onChange={(e)=>{
                    if (e.target.checked) {
                      setSelectedSubCats([...selectedSubCats, e.target.value]);
                      setSubCategoryName([...subCategoryName,e.target.name])
                    } else {
                      const newArr = selectedSubCats.filter((item) => item !== e.target.value);
                      setSelectedSubCats(newArr);
                     const namesArr = subCategoryName.filter((item) => item !== e.target.name)
                     setSubCategoryName(namesArr)
                    }

                  }}
                  text={item.name}
                />
              </div>
            ))}

I am also printing selected subcategories as an array

 {subCategoryName && (subCategoryName.map((name,index)=>(
                 <div key={index}>
                  <button style= type='submit'>{name}<AiOutlineClose/></button>
                 </div>
                 )))}

Is there a way to uncheck a selected checkbox from these buttons by passing id? or calling functions. I do not want all checkboxes to be unchecked, only from the selected buttons




Aucun commentaire:

Enregistrer un commentaire