April 15, 2017

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:

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

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.

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

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

The code should looks like something below now: