EN
React - increment state value (class component)
0 points
In this article, we would like to show you how to increment state value in React.
Quick solution:
xxxxxxxxxx
1
this.setState({ value: this.state.value + 1 })
Below example presents how to create a simple counter using a component's state
. With setState
method, we increment value
on every click event.
Runnable example:
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
// import React from react';
3
4
class App extends React.Component {
5
constructor(props) {
6
super(props);
7
this.state = {
8
value: 0,
9
};
10
}
11
render() {
12
return (
13
<div>
14
<button onClick={() => this.setState({ value: this.state.value + 1 })}>
15
click me
16
</button>
17
<br />
18
<label>{this.state.value}</label>
19
</div>
20
);
21
}
22
}
23
24
const root = document.querySelector('#root');
25
ReactDOM.render(<App />, root );