简体   繁体   中英

How to use checkbox as Radio Button in ReactJS with hooks?

I'm Building a filter in ReactJS with hooks and now I need apply some style to the checkboxes.. The CSS is not the problem, I already did it in vanilla:

function checkOne(checkbox) {

    var checkboxes = document.getElementsByName('plan')

    checkboxes.forEach((item) => {

        item !== checkbox ? item.checked = false : item.checked = true;

    })

}

=======================================================================
                             X 3

                  <label for="premium">
                      <input 
                        type="checkbox" 
                        name="plan" 
                        onclick="checkOne(this)"
                        class="input-check" 
                        value="Premium"
                       >
                      <span 
                       class="checkmark" 
                       id="premium"
                      >
                         Premium
                     </span>           
                 </label>

Now I need to do the same think in react with hooks and I get stuck, I'm mapping a source of products and making a list of checkboxes form the product categories...

... 

const [checked, setChecked] = useState(false) //hook

...

handleChange(e, checkbox){
      setProduct(e.target.value);
      setSearch(e.target.value);      

 let checkboxes = document.getElementsByName('products')

    checkboxes.forEach((item) => {

        item !== checkbox ? setChecked(false) : setChecked(true);

    })
}

... in render method

      <div className="filters" id="top">
         {uniqueProduct.map(product => (    
             <label key={product.id}>
                <input
                      className='filters-available-size'
                      type="checkbox"
                      value={product.category}
                      onChange={handleChangeProduct} // <-- ?¿?¿ what should go here?
                      name='product'
                   />
                   <span className="checkmark">
                       {product.category}
                   </span>
             </label>
          ))}
        </div>

Why do you need to use checkboxes as radio buttons? I'm going to assume because of the styling--a design decision, perhaps. In which case, I would use radio buttons for the functionality and then use CSS to hide radio buttons and show checkboxes that reflect the state of the chosen option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM