Using Radio Button in React

Using Radio Button in React

The way we use radio buttons in React is different from the way we usually do ... In this tutorial, we're going to make a simple.

Today In this React tutorial, we will explore how to work with Radio buttons in React app. Radio buttons are HTML elements and help the user to choose one option among two or more than two options. In this tutorial, we will learn how to use Radio buttons in React app. Using radio buttons in React is a little bit different than we use in regular HTML. However, we will learn the effortless way to integrate Radio buttons in React.

React Radio Button Example

In this React radio buttons tutorial, we are going to create a basic form in React component using render() method. This form will have five color options, among which a user can choose his favorite color. When a user clicks on the submit button, the radio button state will change.

Basic React App Set Up

Let’s start by installing and setting up the basic React app to show the radio buttons example.

npx create-react-app react-radio-buttons

Enter inside the `react-radio-buttons` project.

cd react-radio-buttons

Run the command to start the React app:

npm start

Define React Radio Button State

Firstly, we will set the radio buttons state. This Radio button state is being referred to as the user’s selection. We set defined the color variable in state and assign the empty (‘ ‘) value in it because the user will choose the color once the form is ready.

class App extends Component {

constructor() {
super();

this.state = {
  color: ''
};

}

}

Build React Form with React Render Method

In this step, we will define the HTML form with radio buttons along with color values inside the render() method. This method will render 5 Radio buttons wrapped inside the Unordered Lists.

 render() {
return (
<div className="App">
<form onSubmit={this.onSubmit}>
<strong>Select Color:</strong>

      &lt;ul&gt;
        &lt;li&gt;
          &lt;label&gt;
            &lt;input
              type="radio"
              value="red"
              checked={this.state.color === "red"}
              onChange={this.onRadioChange}
            /&gt;
            &lt;span&gt;Red&lt;/span&gt;
          &lt;/label&gt;
        &lt;/li&gt;

        &lt;li&gt;
          &lt;label&gt;
            &lt;input
              type="radio"
              value="green"
              checked={this.state.color === "green"}
              onChange={this.onRadioChange}
            /&gt;
            &lt;span&gt;Green&lt;/span&gt;
          &lt;/label&gt;
        &lt;/li&gt;

        &lt;li&gt;
          &lt;label&gt;
            &lt;input
              type="radio"
              value="blue"
              checked={this.state.color === "blue"}
              onChange={this.onRadioChange}
            /&gt;
            &lt;span&gt;Blue&lt;/span&gt;
          &lt;/label&gt;
        &lt;/li&gt;

        &lt;li&gt;
          &lt;label&gt;
            &lt;input
              type="radio"
              value="orange"
              checked={this.state.color === "orange"}
              onChange={this.onRadioChange}
            /&gt;
            &lt;span&gt;Ornage&lt;/span&gt;
          &lt;/label&gt;
        &lt;/li&gt;

        &lt;li&gt;
          &lt;label&gt;
            &lt;input
              type="radio"
              value="purple"
              checked={this.state.color === "purple"}
              onChange={this.onRadioChange}
            /&gt;
            &lt;span&gt;Purple&lt;/span&gt;
          &lt;/label&gt;
        &lt;/li&gt;
      &lt;/ul&gt;

      &lt;button type="submit"&gt;Choose Color&lt;/button&gt;
    &lt;/form&gt;
  &lt;/div&gt;
);

}

Let us understand what we did in the form. We defined color values in every radio button along with two properties checked and onChange.

The checked prop in our form is managing the selection of a radio button based on the radio button’s color state.

We are validating every radio buttons state with its respective value. When the value is checked, it will be set to true, and the radio button is considered to be selected. If the value is false, then the radio button will be in the unselected state

How is it working?

Well, when a user clicks on any of the radio buttons from the defined group. Then we are updating the state via color variable using the onChange event handler.

Lastly, we declared the onSubmit event handler and attached with the onSubmit method to the main form. So when the user clicks on the submit button, then the radio buttons value gets updated.

Radio Button Selected State in React

We define the value of a Radio button with the state variable. It sets the selected value of a Radio button in React.

class App extends Component {

constructor() {
super();

this.state = {
  color: 'green'
};

}

}

It will look something like this in your browser:

Include Event Handler in React Form

In this step, we will include the event handler. This will set and update the sate of Radio button when a user clicks on the radio button.

  onRadioChange = (e) => {
this.setState({
color: e.target.value
});
}

The above method will update the color value of a Radio button when change by the user.

The Final Touch

In this final step we will define the onSubmit event handler to the form, this event will trigger when a user submits the form.

Use the event.preventDefault() method, it helps in fixes the page redirecting issue when a user clicks on the submit button.

import React, { Component } from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

class App extends Component {

constructor() {
super();

this.state = {
  color: 'green'
};

this.onRadioChange = this.onRadioChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);

}

onRadioChange = (e) => {
this.setState({
color: e.target.value
});
}

onSubmit = (e) => {
e.preventDefault();
console.log(this.state);
}

render() {
return (
<div className="App">
<form onSubmit={this.onSubmit}>
<strong>Select Color:</strong>

      &lt;ul&gt;
        &lt;li&gt;
          &lt;label&gt;
            &lt;input
              type="radio"
              value="red"
              checked={this.state.color === "red"}
              onChange={this.onRadioChange}
            /&gt;
            &lt;span&gt;Red&lt;/span&gt;
          &lt;/label&gt;
        &lt;/li&gt;

        &lt;li&gt;
          &lt;label&gt;
            &lt;input
              type="radio"
              value="green"
              checked={this.state.color === "green"}
              onChange={this.onRadioChange}
            /&gt;
            &lt;span&gt;Green&lt;/span&gt;
          &lt;/label&gt;
        &lt;/li&gt;

        &lt;li&gt;
          &lt;label&gt;
            &lt;input
              type="radio"
              value="blue"
              checked={this.state.color === "blue"}
              onChange={this.onRadioChange}
            /&gt;
            &lt;span&gt;Blue&lt;/span&gt;
          &lt;/label&gt;
        &lt;/li&gt;

        &lt;li&gt;
          &lt;label&gt;
            &lt;input
              type="radio"
              value="orange"
              checked={this.state.color === "orange"}
              onChange={this.onRadioChange}
            /&gt;
            &lt;span&gt;Ornage&lt;/span&gt;
          &lt;/label&gt;
        &lt;/li&gt;

        &lt;li&gt;
          &lt;label&gt;
            &lt;input
              type="radio"
              value="purple"
              checked={this.state.color === "purple"}
              onChange={this.onRadioChange}
            /&gt;
            &lt;span&gt;Purple&lt;/span&gt;
          &lt;/label&gt;
        &lt;/li&gt;
      &lt;/ul&gt;

      &lt;button type="submit"&gt;Choose Color&lt;/button&gt;
    &lt;/form&gt;
  &lt;/div&gt;
);

}
}

export default App;

Following will be the output:

The React Radio button tutorial with example is completed.

Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!

Further reading

☞ React - The Complete Guide (incl Hooks, React Router, Redux)

☞ Modern React with Redux [2019 Update]

☞ Best 50 React Interview Questions for Frontend Developers in 2019

☞ Best JavaScript Frameworks, Libraries and Tools to Use in 2019

☞ React vs Angular vs Vue.js by Example

ReactJS Development Company in Canada| Hire React JS Developers

a successful and trustworthy ReactJS development company in Ontario, Canada with presence in India. Hire our professional React JS developer who will guarantee you the custom ReactJS development and create bug-free, creative, seamless and interactive user interface apps. Get our services at the most competitive prices.

Top React Native Developers in the USA

For most mobile app development company it is incredibly important to maintain shorter development cycles while not compromising on feature set or cross-platform native performance. Often developers need to ensure any one if these at the expense of others. React Native is one of the development languages that ensure fast-paced development by reusing codes while boosting the apps with native capabilities.

Website: Top React Native Developers in USA

What are hourly rates to hire React Native App Development Company?

What are hourly rates to hire React Native App Development Company?

HireFullStackDeveloperIndia is a top provider of React Native for Mobile App Development and cross-platform mobile app development.

Cross-platform mobile application development provides the user experience and functionality of native apps with the multi-platform compatibility of mobile apps. Explore all the details related to building your React Native mobile applications here and get the idea of the hourly hiring charges for React Native app development.

HireFullStackDeveloperIndia is a top provider of React Native for Mobile App Development and cross-platform mobile app development services in India & the USA. It specializes in full-service iOS/Android app development process right from requirements gathering, UX/UI design, coding, testing to product maintenance and support to build fully-featured & quality-rich mobile apps.

As a Top Mobile App Development Company in India provides end-to-end Apps Development Services to transform an idea into a successful mobile application that performs flawlessly in the entire Android ecosystem. Their app development covers connected devices, wearable, smart TVs and in-car infotainment systems. This mobile app development company is working in this business from last one and half decade offering the best result for the clients. They are also able to deliver customized, reliable and efficient mobile app development solutions to the clients.

Right from Mobile Strategy to Mobile app design and development to mobile app testing and deployment, they adhere to proven global standards and methodology to deliver top-ranking mobile apps. They develop and deploy mobility solutions that encompass strategy and industry-specific accelerators aimed towards transformation and building a future-proof organization.

Mobile App Development Services by Full Stack Developers:

  • iOS App Development(iPhone & iPad)
  • Android App Development
  • Windows App Development
  • Cross-platform App Development
  • React Native Mobile App Development

HireFullStackDeveloperIndia Top React Native Developers generally charge the range rates of $12- $18 per hour which depends on your requirement. The cost will be decided on the basis of requirement, product features, an experience level of the developer and many other factors.

To be precise, HireFullStackDeveloperIndia can be your mobile app development partner for the consistent growth of your business. Just get in touch with your Mobile App project requirements, as they can help you in creating an idea for project completion using excellent methodology.