EN
React - radio button example (controlled components)
3 points
In this article we would like to show you how to use React radio button
.
Quick solution:
xxxxxxxxxx
1
// stores current selection
2
const [gender, setGender] = useState();
3
4
// handles selection change
5
const handleChange = e => {
6
const target = e.target;
7
if (target.checked) {
8
setGender(target.value);
9
}
10
};
11
12
// example radio button (use it multiple times your source code)
13
<label>
14
<input type="radio" value="male" checked={gender == 'male'} onChange={handleChange} />
15
<span>Male</span>
16
</label>
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:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from react';
3
// import ReactDOM from 'react-dom';
4
5
const Form = props => {
6
const [gender, setGender] = React.useState();
7
const handleChange = e => {
8
const target = e.target;
9
if (target.checked) {
10
setGender(target.value);
11
}
12
};
13
const handleSubmit = e => {
14
e.preventDefault();
15
console.log(gender);
16
};
17
return (
18
<form onSubmit={handleSubmit}>
19
<div>
20
<label>
21
<input type="radio" value="male" checked={gender == 'male'} onChange={handleChange} />
22
<span>Male</span>
23
</label>
24
<label>
25
<input type="radio" value="female" checked={gender == 'female'} onChange={handleChange} />
26
<span>Female</span>
27
</label>
28
</div>
29
<button type="submit">Submit</button>
30
</form>
31
);
32
};
33
34
const root = document.querySelector('#root');
35
ReactDOM.render(<Form />, root );
Important note:
When you create forms, React recommends using uncontrolled components,
because with controlled components large amount of input elements withonChange
event handling leads to performance degradation by component multiple re-rendering.