React - Write a Simple Counter

Tell us what’s happening:

.inc and .dec are not working???

Your code so far

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
    // Change code below this line
    this.reset = this.reset.bind(this);
    this.increment = this.increment.bind(this);
    this.decrement = this.decrement.bind(this);
    // Change code above this line
  }
  // Change code below this line
  increment() {
    this.setState((state) => {
      count: state.count + 1
    })
  }
  decrement() {
    this.setState((state) => {
      count: state.count - 1
    })
  }
  reset() {
    this.setState({
      count: 0
    })
  }
  // Change code above this line
  render() {
    return (
      <div>
        <button className='inc' onClick={this.increment}>Increment!</button>
        <button className='dec' onClick={this.decrement}>Decrement!</button>
        <button className='reset' onClick={this.reset}>Reset</button>
        <h1>Current Count: {this.state.count}</h1>
      </div>
    );
  }
};

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36

Challenge Information:

React - Write a Simple Counter

Silly me! I just forgot to put the object of the increment and decrement functions inside parentheses! Solved.

I did:

this.setState((state) => {
  count: state.count - 1
})

instead of:

this.setState((state) => ({
  count: state.count - 1
}))

Note the opening parenthesis after the => arrow, and the closing parenthesis after the closing curly brace }.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.