Languages
[Edit]
EN

React - increment state value (class component)

0 points
Created by:
cory
1756

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

Alternative titles

  1. React - counter in state (class component)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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