How to keep only one radio button selected with React
Asked Answered
W

3

6

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>
    )
  }
});
Weksler answered 14/6, 2015 at 15:55 Comment(0)
S
15

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>
Schnorrer answered 14/6, 2015 at 16:13 Comment(0)
P
1

Add property checked and do comparation there.

Example: checked={this.state.myValue === true}

I will give you working example, two radio buttons controls value between true/false.

https://jsfiddle.net/4hs7v5qb/1/

Penetration answered 23/9, 2020 at 8:49 Comment(1)
This is the easiest way to implement the solution.Flunk
S
0

Just tweaking Chad's answer just in case someone runs into this.

<input type="radio" name="myGroupName" onChange={this.handleChange}/>
<span>{this.props.myValue}</span>

Don't add any children to the input element as React will throw an error. Just use a span or label next to it for the visible text.

Swayne answered 3/3, 2018 at 17:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.