Languages
[Edit]
EN

React - increment state value (class component)

0 points
Created by:
Dirask Community
6240

In this article, we would like to show you how to increment state value in React.

Quick solution:

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:

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from react';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 0,
    };
  }
  render() {
    return (
      <div>
        <button onClick={() => this.setState({ value: this.state.value + 1 })}>
          click me
        </button>
        <br />
        <label>{this.state.value}</label>
      </div>
    );
  }
}

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

ReactJS

React - increment state value (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