Radio Button in React

In this article, we will learn the basics of the radio button in the React.js application.

Prerequisites of React

  • Familiarity with HTML and JavaScript.
  • node.js installed

Create React Project

To create a React app, use the following command in the terminal.

npx create-react-app matui

Install Bootstrap

Now install Bootstrap by using the following command.

npm install bootstrap

Now, open the index.js file and add the import Bootstrap.

import 'bootstrap/dist/css/bootstrap.min.css';

Now right-click on the src folder, create a new component named 'radiobtndemo.js', and follow the code. In this file, we have created a class component in reactjs

import React, { Component } from "react";

class Radionbtn extends Component {
    constructor() {
        super();
        this.state = {
            name: "React"
        };
        this.onValueChange = this.onValueChange.bind(this);
    }

    onValueChange(event) {
        this.setState({
            selectedOption: event.target.value
        });
    }

    formSubmit(event) {
        event.preventDefault();
        console.log(this.state.selectedOption)
    }

    onChangeValue(event) {
        console.log(event.target.value);
    }

    render() {
        return (
            <div>
                 <div class="col-sm-12 btn btn-info"> How to Use Radio Button in React</div>
            
            <form>
                <div className="radio">
                    <label>
                        <input 
                            type="radio"
                            value="Male"
                            checked={this.state.selectedOption === "Male"}
                            onChange={this.onValueChange}
                        />
                        Male
                    </label>
                </div>
                <div className="radio">
                    <label>
                        <input
                            type="radio"
                            value="Female"
                            checked={this.state.selectedOption === "Female"}
                            onChange={this.onValueChange}
                        />
                        Female
                    </label>
                </div>
                <div>
                    Selected option is : {this.state.selectedOption}
                </div>
            </form>
            </div>
        );
    }
}

export default Radionbtn;

Now, import the radiobtndemo component in the src/App.js file.

import './App.css';
import Radionbtn from './radiobtndemo'
function App() {
  return (
    <div className="App">
      <Radionbtn/>
    </div>
  );
}

export default App;

Now, run the project using the 'npm start' command and check the result.

Radio button in React

Summary

In this article, we learned the basics of the radio button in the React.js application.