Languages
[Edit]
EN

React - radio button example (controlled components)

3 points
Created by:
Rubi-Reyna
677

In this article we would like to show you how to use React radio button.

Quick solution:

// stores current selection
const [gender, setGender] = useState();

// handles selection change
const handleChange = e => {
   const target = e.target;
   if (target.checked) {
     setGender(target.value);
   }
};

// example radio button (use it multiple times your source code)
<label>
 <input type="radio" value="male" checked={gender == 'male'} onChange={handleChange} />
 <span>Male</span>
</label>

 

Practical example

Below example shows a form as a functional component with two radio buttons representing Male and Female.

With useState we are able to keep the data in component's state. In our case it's one of two genders: male or female. When onChange event occurs then setGender updates the state of a component the selected radio button's value.

JSX version:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from react';
// import ReactDOM from 'react-dom';
   
const Form = props => {
  const [gender, setGender] = React.useState();
  const handleChange = e => {
    const target = e.target;
    if (target.checked) {
      setGender(target.value);
    }
  };
  const handleSubmit = e => {
    e.preventDefault();
    console.log(gender);
  };
  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>
          <input type="radio" value="male" checked={gender == 'male'} onChange={handleChange} />
          <span>Male</span>
        </label>
        <label>
          <input type="radio" value="female" checked={gender == 'female'} onChange={handleChange} />
          <span>Female</span>
        </label>
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<Form />, root );

Important note:
When you create forms, React recommends using uncontrolled components,
because with controlled components large amount of input elements with onChange event handling leads to performance degradation by component multiple re-rendering.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - radio button example
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join