How to create gender radio button in react js?

Hi Friends πŸ‘‹,

Welcome To aHoisting!

To create gender radio button in react js, you have to use useState from and input. It will create gender radio button in react js.

Today, I am going to show you, how to create gender radio button in react js.

Table of contents

  • Install and create a new React app.
  • Import react component.
  • Create a Component.

Let’s start with the first step.

Step 1: Install and create a new React app.

First you have to install the React project. You should use create-react-app command to create a new React project.

npx create-react-app my-app
cd my-app
npm start

Step 2: Import react component.

After installing, you have to import your React component.

import React, { useState } from 'react';

Step 3: Create a Component.

You can use checked={gender === 'Male'} in <input> to create gender radio button in react js.

<form onSubmit={handleSubmit}>
  <label>
    <input
          type="radio"
          value="Male"
          checked={gender === 'Male'}
          onChange={handleChange}
        />
        Male
      </label>
      <label>
        <input
          type="radio"
          value="Female"
          checked={gender === 'Female'}
          onChange={handleChange}
        />
        Female
      </label>
      <label>
        <input
          type="radio"
          value="Other"
          checked={gender === 'Other'}
          onChange={handleChange}
        />
        Other
      </label>
  <button type="submit">Submit</button>
</form>

Create gender radio button example.

The below code is an example of a React. You have to import react and set checked={gender === 'Male'} in <input> to create gender radio button in react js.

App.js

import React, { useState } from 'react';

const GenderRadioButton = () => {
  const [gender, setGender] = useState('');

  const handleChange = (event) => {
    setGender(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`Selected Gender: ${gender}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        <input
          type="radio"
          value="Male"
          checked={gender === 'Male'}
          onChange={handleChange}
        />
        Male
      </label>
      <label>
        <input
          type="radio"
          value="Female"
          checked={gender === 'Female'}
          onChange={handleChange}
        />
        Female
      </label>
      <label>
        <input
          type="radio"
          value="Other"
          checked={gender === 'Other'}
          onChange={handleChange}
        />
        Other
      </label>

      <button type="submit">Submit</button>
    </form>
  );
};

export default GenderRadioButton;

In the above code example, I have used the checked={gender === 'Male'} to create gender radio button in react js.

Check the output of the above code.

React, create, gender, radio, button

All the best πŸ‘