EN
React - checkbox example
3 points
In this article, we would like to show you how to use a checkbox in React.
Below example shows a form
as a functional component with a single checkbox
and submit button.
We use useState
hook to store boolean agreement
state and setAgreement
function to modify it.
Quick solution:
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
//import React from 'react';
3
4
const Form = props => {
5
const [agreement, setAgreement] = React.useState(false);
6
const handleChange = e => setAgreement(e.target.checked);
7
const handleSubmit = e => {
8
e.preventDefault();
9
console.log(`checked: ${agreement}`);
10
};
11
return (
12
<form onSubmit={handleSubmit}>
13
<div>
14
<label>
15
<input type="checkbox" checked={agreement} onChange={handleChange} />
16
<span>Consent to the data processing</span>
17
</label>
18
</div>
19
<button type="submit">Submit</button>
20
</form>
21
);
22
};
23
24
const root = document.querySelector('#root');
25
ReactDOM.render(<Form />, root );
Note:
Go to this article to see class component example.