Languages
[Edit]
EN

React - radio button example (controlled components)

3 points
Created by:
Dirask Community
3960

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

Quick solution:

// keeped state:
const [gender, setGender] = useState();

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

// radio input element (for 'male' value; we can use it many times for different values):
<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.

ReactJS

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