Home > Back-end >  Allow users to uncheck radio buttons in react
Allow users to uncheck radio buttons in react

Time:07-07

The problem: I have a selection of 3 radio buttons, and I need to allow users to unselect a radio button they have previously selected by clicking on it (toggle state based on user selection of radio button). Adding a "none" or "clear selections" button is not an option. So this needs to be either radio buttons that allow un-selecting, or checkboxes that allow only 1 selection.

How on earth do I do this in react cleanly? Semi-cleanly?

Disclaimers:

  1. I have searched google and SO and found nothing that answers my questions, either b/c they don't solve my particular problem, or I am unknowingly misunderstanding them.
  2. Yes I know this is not what radio buttons/checkboxes are designed to do, but this is what the client wants and I cannot push back on this decision any further
  3. I'm very new to react, so apologies if the answer is obvious and I just missed it.

CodePudding user response:

Mhm, this solution is not great, but, you can do the following:

  • onChange -> you just switch the state
  • onClick -> verify if the value is the one that you're already having in the state. If so, set the state to null.

Look at this CodeSandbox

Or, you can use a checkbox, and always keep 1 item in state at a time. And once that is clicked again, just clear the state.

CodePudding user response:

import React from 'react'

const ExclusiveCheckBoxes = (props) => {
    const allUnchecked = {option1:false, option2:false, option3:false};
    const [options, setOptions] = React.useState(allUnchecked);

    const chkChanged  = e => {
        setOptions({...allUnchecked, [e.target.name]: e.target.checked});
    }

   return (
       <div>
           <h1>ExclusiveCheckBoxes</h1>
           <input type="checkbox" name="option1" 
                checked={options.option1} onChange={chkChanged}/>
           <input type="checkbox" name="option2" 
                checked={options.option2} onChange={chkChanged}/>
           <input type="checkbox" name="option3" 
                checked={options.option3} onChange={chkChanged}/>
       </div>
   )
}

export default ExclusiveCheckBoxes

  • Related