ReactJS Radio Button Example

Share the post

Hello Everyone, In this ReactJS tutorial, We will see ReactJS Radio Button Example. We will select the value onChange() method. When we select any value using the radio button then we will get that value.

In the previous ReactJS tutorial, We had discussed How to upload the image file and preview it using reactjs. Now, in this ReactJS Radio Button Example, We will get the appropriate selected radio button value.

So, Let’s Start…

ReactJS Radio Button Example | Get Selected Value using onChange()

  • Step1: Create a new React Application
  • Step2: Write the code
  • Step3: Run the React Application
  • Step4: Output

Step1: Create a new React Application

We need to create a new ReactJS Project. Use the below command to create a new project in ReactJS.

npx create-react-app myapp

Now, go to navigate to the project path as shown below

cd myapp

We will open this project in the Visual Studio Code editor using the following command.

code .

Step2: Write the Code

Now, We have to take 1 div tag including 3 input tags who are having type as radio. Then, We will write onChange() method on div. So, Whenever we change the selection on the radio button it will call this onChange() method. In the onChange() method we will get the selected radio value using the event.

Full App.js

import React, { useState } from "react";

const App = () => {

  const handleRadioSelection = (event) => {
    console.log(event.target.value);
    alert("You have selected " + event.target.value);
  };
  return (
    <>
      <div onChange={handleRadioSelection}>
        <input type="radio" value="Maths" name="subject" /> Maths
        <input type="radio" value="English" name="subject" /> English
        <input type="radio" value="History" name="subject" /> History
      </div>
    </>
  );
}

export default App;

Step3: Run the React Application

Now, Run the React Application using the below command.

npm run start

Step4: Output

Now, We can check the output in the browser. Please see the below output.

ReactJS Radio Button Example
ReactJS Radio Button Example

Leave a Comment