Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React radio button not update selection

Trying React radio but the strange thing is that the radio selection will not update its view. Can anyone take a look at the code below and let me know what's wrong?

  class Test extends React.Component {
    constructor(props){
    super(props);

    this.state = {
      radioVal: "first"
    }
  }

  handleRadioSelection(e){
    e.preventDefault();

    this.setState({
      radioVal:e.target.value
    })
  }

    render(){
      return (
        <div>
            <label>
            <input type="radio" onChange={this.handleRadioSelection.bind(this)} 
            checked={ this.state.radioVal==="first"} 
            value="first" 
            name="radio1" /> 1 <br />
          </label>

          <label>
            <input type="radio" onChange={this.handleRadioSelection.bind(this)} 
            checked={this.state.radioVal==="second"} 
            value="second" 
            name="radio1" /> 2 <br />
          </label>
            { "Selected: " } {this.state.radioVal}
        </div>
    )
  }
}

React.render(<Test />, document.getElementById('container'));
like image 277
max li Avatar asked Oct 18 '22 14:10

max li


1 Answers

Remove e.preventDefault(); from handleRadioSelection. Is there a reason why you added that line in the first place?

like image 144
Yangshun Tay Avatar answered Oct 20 '22 23:10

Yangshun Tay