Uncheck radio buttons in react

Viewed 33211

I think its a very silly doubt but I am stuck in this.. I have multiple radio buttons and I want to uncheck all the radio buttons as soon as I click the other radio button. How can I achieve it in react?

var options = [{id:1,nm:"Appointment fixed"},{id:2,nm:"Call later"},{id:3,nm:"Wrong number"},{id:4,nm:"Don't call again"},{id:5,nm:"Call later"}];
{options.map((item,i) => {
                     return (
                        <div onChange={(i)=>this.callOptions(i)}>
                           <label className="radio-inline"><input type="radio" value={i} ref={'ref_' + i} value={item.id}/>{item.nm}</label>
                        </div>
                      )
                  })}
4 Answers

I was trying this on react with bootstrap and I faced the same issue. What you can do is check if the radio button was clicked by using e.target.checked and then check it again with the previous state of the checked value set in state.

For Example this is what's in the render method

<input checked={this.state.radioButton} onClick={this.onClickAvailability} className="form-check-input" type="radio" value="Click" />
<label>Click</label>

And in the event handler

onClickAvailability(e){

            if(e.target.checked && !this.state.radioButton){
                this.setState({
                    radioButton:true,
                })
            }else if(e.target.checked && this.state.radioButton){
                this.setState({
                    radioButton:false,
                })

     }

Please remember to set the initial value to false at the componentDidMount or in the constructor

Related