How to use Radio Buttons in React

How to use Radio Buttons in React

In this post we will give you information about How to use Radio Buttons in React. Hear we will give you detail about How to use Radio Buttons in ReactAnd how to use it also give you demo for it if it is necessary.

we are going to learn about how to use radio buttons in react with class-based components and hooks.

Radio buttons

Radio buttons are used to select exactly one option from the available list, for example, choose the correct answers.

Using Radio buttons in React

To use the radio buttons in react we need to group the radio buttons with a name attribute and onChange event handler method is added to each radio button to access the data.

Here is an example:

import React,{Component} from 'react';class App extends Component {    state = {      gender:""    };    handleChange=(e)=>{        this.setState({          gender: e.target.value        })    }  render() {    return (      <div>         <form>            <input type="radio" value="male" id="male"              onChange={this.handleChange} name="gender" />            <label for="male">Male</label>            <input type="radio" value="female" id="female"              onChange={this.handleChange} name="gender"/>            <label for="female">Female</label>         </form>         <p>You gender is --> {this.state.gender}</p>      </div>    );  }}

In the above code, we have grouped two radio buttons with a name attribute value to gender.

When a user selects the radio button handleChange() method is invoked and access the radio button value to update the state.

Output:

Using Radio buttons in React Hooks

Let’s see how to use the radio button in hooks.

<span>import React, { useState } from 'react';function App() {   const [gender,setGender]=useState('');   const handleChange=(e)=&gt;{       setGender( e.target.value);    }    return (      &lt;div&gt;         &lt;form&gt;             &lt;input type="radio" value="male" id="male"               onChange={handleChange} name="gender" /&gt;             &lt;label for="male"&gt;Male&lt;/label&gt;            &lt;input type="radio" value="female" id="female"              onChange={handleChange} name="gender"/&gt;            &lt;label for="female"&gt;Female&lt;/label&gt;         &lt;/form&gt;         &lt;p&gt;You gender is --&gt; {gender}&lt;/p&gt;      &lt;/div&gt;    );}

Hope this code and post will helped you for implement How to use Radio Buttons in React. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US