React dealing with radios button

By default when you create radio multiple radios with same names, check either one will uncheck the rest.

  
  
  

Try out above codes.

In jQuery we can get the value of the radio easily using:

  $('input[name="radio1"]').val();

In react we have use state to get the value of current selected radio:

  class Test extends React.Component {
      handleRadioSelection(e){
      console.log(e.target.value);
  }
  
	render(){
		return (
      	
1
2
3
4
) } } React.render(, document.getElementById('container'));

We can get the value of this from “handleRadioSelection” method, but we can’t get the radio button selected. You may try adding checked=”true” you will get this radio checked, but you no way other radio will be checked if you click any other of them.

So how we do solve this?

since we know that we could use checked=”true” for checked item, we want to set the rest false and when selecting this radio. Lets do it with states, lets try with the concept if this.state.radioVal == this value then set true for this radio to be checked.

   1 
2
3
4

Now lets create our state initialiser, and select radio 1 as default,

  constructor(){
    this.states = {
      radioVal: 1
    }
  }

Then we need onChange to change the value of this radioVal state:

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

The code should looks like something below now:

class Test extends React.Component {
  constructor(props){
    super(props);
    
    this.state = {
      radioVal: "first"
    }
  }
  
  handleRadioSelection(e){
    this.setState({
      radioVal:e.target.value
    })
  }
  render(){
    return (
      	
1
2
3
4
) } } React.render(, document.getElementById('container'));