Hello Devs,


In this tutorial, we are going to learn how to use radio button in react js.

Given below is the example code and the output:




Example Code:

import React, { Component } from 'react';
import { render } from 'react-dom';
      
class App extends Component {
  constructor() {
    super();
    this.state = {
      gender: ''
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
    
  handleChange(event) {
    this.setState({gender: event.target.value});
  }
    
  handleSubmit(event) {
    console.log(this.state);
    event.preventDefault();
  }
    
  render() {
    return (
      <div>
        <h1>React Radio Buttons onChange Example - Rathorji.in</h1>
        <form onSubmit={this.handleSubmit}>
          
          <strong>Select Gender:</strong>
          <label> 
            <input
              type="radio"
              value="male"
              onChange={this.handleChange}
            />Male
          </label>
          <label> 
            <input
              type="radio"
              value="female"
              onChange={this.handleChange}
            />Female
          </label>
          
          <input type="submit" value="Submit" />
        </form>
      </div>
    );
  }
}
  
render(<App />, document.getElementById('root'));


OUTPUT:

{gender: "male"}


I hope this example helps you.