React: Write a Simple Counter

Going through the React challenges on the beta version of FCC. Stuck at Write a Simple Counter.

Challenge: The Counter component keeps track of a count value in state. There are two buttons which call methods increment() and decrement(). Write these methods so the counter value is incremented or decremented by 1 when the appropriate button is clicked. Also, create a reset() method so when the reset button is clicked, the count is set to 0.

Note: Make sure you don’t modify the classNames of the buttons.

My code:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };

  // change code below this line

  increment() {
    this.setState({
      this.state.count: this.state.count + 1
    });
  };
  
  decrement() {
    this.setState({
      this.state.count: this.state.count - 1
    });
  };

  reset() {
    this.setState({
      this.state.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>
    );
  }
};

What am I doing wrong?

OK…so this is a trick question. you still need the binding statements in the constructor. I was just now able to get mine to go through.

1 Like

You need to bind statements in the constructor.

 this.increment = this.increment.bind(this)
 this.decrement = this.decrement.bind(this)
 this.reset = this.reset.bind(this)
2 Likes

Is there anyway of doing this without 3 bind statements?

You can with an anonymous arrow function in Render event handlers.

I found this helpful. https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  // change code below this line

  increment() {
    this.setState({
      count: this.state.count + 1
    });
  };
  
  decrement() {
    this.setState({
      count: this.state.count - 1
    });
  };

  reset() {
    this.setState({
      count: 0
    });
  };

  // change code above this line
  render() {
    return (

   <div>
   <button className='inc' onClick={(e) => this.increment(e)}>Increment!</button>
    <button className='dec' onClick={(e) => this.decrement(e)}>Decrement!</button>
    <button className='reset' onClick={(e) => this.reset(e)}>Reset</button>
    <h1>Current Count: {this.state.count}</h1>
  </div>
    );
  }
};

try with

this.setState({
count : this.state.count + 1
})

Click