Languages
[Edit]
EN

React - update state with onClick (class component)

0 points
Created by:
Zoya-Gaines
293

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 );

ReactJS

React - update state with onClick (class component)
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join