0

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>

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You're right, I wanted to see if it was possible to do it but it's not worth it in this case. Thanks for your help.

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.