Categories
React Answers

How to use radio buttons in React?

Spread the love

Sometimes, we want to use radio buttons in React.

In this article, we’ll look at how to use radio buttons in React.

How to use radio buttons in React?

To use radio buttons in React, we can set a state to the selected radio button’s value attribute value.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [gender, setGender] = useState();
  console.log(gender);

  return (
    <div>
      <input
        type="radio"
        value="male"
        name="gender"
        onChange={(e) => setGender(e.target.value)}
      />
      Male
      <input
        type="radio"
        value="female"
        name="gender"
        onChange={(e) => setGender(e.target.value)}
      />
      Female
    </div>
  );
}

We add 2 radio buttons by adding input elements.

And we set the name attribute of them to the same value to put them in the same group.

Next, we set the onChange prop of each radio input to a function that calls the setGender function to set gender to the value of the value attribute of the radio button that’s selected.

e.target.value has the value of the value attribute.

As a result, when we click on a radio button, the latest value of gender is logged.

Conclusion

To use radio buttons in React, we can set a state to the selected radio button’s value attribute value.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *