Uncheck radio buttons in react
Give a common name attribute for you radio button. Change
<input type="radio" value={i} ref={'ref_' + i} value={item.id}/>
to
<input type="radio" value={i} name="abc" ref={'ref_' + i} value={item.id}/>
You can either use a controlled input or an uncontrolled input. Below an example for each of the solutions.
Before I post that though, allow me to add some useful tips & links for you:
I've changed the way you use
refs
because your approach is now deprecated and discouraged. Please see this post. Also, you almost certainly don't need anyrefs
here whatsoever; do consider removing them.You're not using the
key
prop for the items you're mapping. I've added that too. Please see this postYou might also want to read about controlled vs uncontrolled inputs. Here's another relevant post I made a while ago.
You have accidentally added two
value
props for your checkbox.
Solutions
Controlled
Add a state variable which is toggled each time you select a radio button. Something like:
constructor() {
super();
this.state = {checkedRadio: null};
}
changeRadio(e) {
this.setState(checkedRadio: e.target.value);
}
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 key={item.id} onChange={(i)=>this.callOptions(i)}>
<label className="radio-inline"><input type="radio" checked={this.state.checkedRadio == i} ref={(el) => this["myRadioRef" + i] = el} value={item.id} onChange={this.changeRadio} />{item.nm}</label>
</div>
);
})}
Uncontrolled
The other option is to use an uncontrolled input. All you need to do to your existing code is to add a name
prop to your inputs. So like:
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 key={item.id} onChange={(i)=>this.callOptions(i)}>
<label className="radio-inline"><input type="radio" name="myRadio" ref={(el) => this["myRadioRef" + i] = el} value={item.id} onChange={this.changeRadio} />{item.nm}</label>
</div>
);
})}