React: Write a Simple Counter

React: Write a Simple Counter
0.0 0

#1

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?


#2

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.


#3

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)

#4

Is there anyway of doing this without 3 bind statements?