Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep only one radio button selected with React

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>
    )
  }
});
like image 380
missingSemicolon Avatar asked Jun 14 '15 15:06

missingSemicolon


1 Answers

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>
like image 88
Chad Taylor Avatar answered Sep 27 '22 00:09

Chad Taylor