Im trying to learn React by doing a small application with it. My application has two radio buttons and I would like to keep always only one of them checked, but cannot seem to figure out how to uncheck the other button when I select the other one. Instead they both remain selected. Here is a jsfiddle for it:
https://jsfiddle.net/4us5us2o/
And here is the code:
var MyRadioButton = React.createClass({
handleChange: function () {
this.props.onChange(this.props.myValue)
},
render: function () {
return (
<input type="radio" onChange={this.handleChange}>{this.props.myValue}</input>
)
}
});
var MyApp = React.createClass({
getInitialState: function () {
return {
selectedValue: ''
}
},
changeValue: function (newValue) {
this.setState({selectedValue: newValue })
},
render: function () {
return (
<div>
<MyRadioButton onChange={this.changeValue} myValue="A" />
<MyRadioButton onChange={this.changeValue} myValue="B" /><br></br>
</div>
)
}
});
You need to provide a name attribute on your input elements to mark them as part of the same radio button group. This standard behavior for an <input> element with type radio.
In your example, you could use:
<input type="radio" name="myGroupName" onChange={this.handleChange}>{this.props.myValue}</input>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With