React Answers

How to use radio buttons in React class-based components?

Spread the love

To use radio buttons in React class-based component, we add inputs with type radio.

For instance, we write

class App extends React.Component {
  setGender(event) {
  render() {
    return ( 
      <div onChange={this.setGender.bind(this)}>
        <input type="radio" value="MALE" name="gender"/> Male
        <input type="radio" value="FEMALE" name="gender"/> Female

ReactDOM.render(<App/>, document.getElementById('app'));

to add 2 radio buttons into the div.

We set the value prop to set the value of when we click on a radio button.

And then we set them to the same name so we can pick on either one to pick a value.

Then we set onChange to this.setGender.bind(this) to get the checked value with when we pick a choice.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.