Ad

ReactJS: How To Use Boolean Values In Radio Buttons?

- 1 answer

What is the proper way to use boolean data in radio buttons. The values will be converted from booleans to strings if used directly.

JSON-data for input fields that is preloaded:

var question = [
  {value: true, name: "Yes"},
  {value: false, name: "Not this time"}
]

The radio button fields:

<input type="radio" 
       name="question" 
       onChange={this.state.onRadioChange} 
       value={this.state.question[0].value} /> {this.state.question[0].name}
<input type="radio" 
       name="question" 
       onChange={this.state.onRadioChange} 
       value={this.state.question[1].value} /> {this.state.question[1].name}

The binding for onRadioChange:

onRadioChange: function(e) {
    console.log(e.target.value);
}

The console log displays that the selected values are converted from booleans to strings.

One way to handle this would be add an extra function to the onRadioChange function to convert "true"/"false" strings to booleans from e.target.value but its feels a bit hackery. Also, using just 'e.target.checked' won't work, because in some radio button groups I have other values than booleans (that needs to be passed through).

Some universal and clean solution would be to use constant values table that is transformed from and to REST.

Are there any special ReactJS way to do it? Maybe not.

Ad

Answer

Currently the solution is to convert the passed attributes from string values to boolean before saving.

var str2bool = (value) => {
   if (value && typeof value === "string") {
        if (value.toLowerCase() === "true") return true;
        if (value.toLowerCase() === "false") return false;
   }
   return value;
}

And calling the conversion:

onRadioChange: function(e) {
    console.log(str2bool(e.target.value));
    // Here we can send the data to further processing (Action/Store/Rest)
}

This way the data is ready to be send through actions to Rest or Stores and it works directly with the radio buttons.

Ad
source: stackoverflow.com
Ad