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:
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 'state value',
};
}
render() {
return (
<div>
<button onClick={() => this.setState({ value: 'updated value' })}>
Update state.
</button>
<br />
<label>{this.state.value}</label>
</div>
);
}
}
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );