EN
React - checkbox example (class component)
0 points
In this article, we would like to show you how to use a checkbox in React.
Below example shows form
as a class component with a single checkbox
and submit button.
We use the component's state to store boolean agreement
which we modify using setState
method.
Practical example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
class Form extends React.Component {
6
constructor(props) {
7
super(props);
8
this.state = {
9
agreement: false
10
};
11
}
12
13
handleChange = e => this.setState({ agreement: e.target.checked });
14
15
handleSubmit = e => {
16
e.preventDefault();
17
console.log(`checked: ${this.state.agreement}`);
18
};
19
20
render() {
21
return (
22
<form onSubmit={this.handleSubmit}>
23
<div>
24
<label>
25
<input type="checkbox"
26
checked={this.state.agreement}
27
onChange={this.handleChange} />
28
<span>Consent to the data processing</span>
29
</label>
30
</div>
31
<button type="submit">Submit</button>
32
</form>
33
);
34
}
35
};
36
37
const root = document.querySelector('#root');
38
ReactDOM.render(<Form />, root);
Note:
Go to this article to see functional component example.