Categories
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) {
    console.log(event.target.value);
  }
  
  render() {
    return ( 
      <div onChange={this.setGender.bind(this)}>
        <input type="radio" value="MALE" name="gender"/> Male
        <input type="radio" value="FEMALE" name="gender"/> Female
      </div>
     )
  }
}

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

to add 2 radio buttons into the div.

We set the value prop to set the value of event.target.valye 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 event.target.value 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.