EN
React - update state with onClick (class component)
0 points
In this article, we would like to show you how to update the state of a component with onClick
event handler in React.
Below example presents how to pass setState
method that updates our state
with new value
to the onClick
event handling function.
Runnable 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 App extends React.Component {
6
constructor(props) {
7
super(props);
8
this.state = {
9
value: 'state value',
10
};
11
}
12
render() {
13
return (
14
<div>
15
<button onClick={() => this.setState({ value: 'updated value' })}>
16
Update state.
17
</button>
18
<br />
19
<label>{this.state.value}</label>
20
</div>
21
);
22
}
23
}
24
25
const root = document.querySelector('#root');
26
ReactDOM.render(<App />, root );