o.O
o.O

Reputation: 501

Iterate on click in React

I am trying to make a component in React where you could iterate +1 or -1 on click. Please look at jsfiddle and tell me where I am missing the point. Many thanks for all possible help.

Looking forward,

 class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {clickCount: 0};
    console.log(this.state)
  } 

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

  handleClickDec(){
     this.setState({count:this.state.clickCount - 1})
  }

 render(){
    return 
    <div>
        <div>
        {this.props.clickCount}
        </div>
        <button onClick={this.handleClickInc}>{"+"}</button>
        <button onClick={this.handleClickDec}>{"-"}</button>
      </div>
  }

}

ReactDOM.render(
  <App/>,
  document.getElementById('container')
);`

html part

<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

Upvotes: 3

Views: 1170

Answers (3)

Nathan Lemke
Nathan Lemke

Reputation: 1

Well first of all all render elements must have return right? So your return is missing the () wrapping the div.

Second, to use state in a function you have to bind the function. I use to put the statement inside the constructor.

You can put like this:

this.handleClickInc = this.handleClickInc.bind(this);

Make this for the other function and it will work.

Upvotes: 0

Christopher Messer
Christopher Messer

Reputation: 2090

Your problems were:

1) your return function was not wrapped in parens, causing a syntax error.

2) your click handlers were not bound to this (i.e. you needed to call this.handleClickInc.bind(this) or use fat arrow syntax as mentioned above.

3) As mentioned, you were updating the state of count but you meant to update clickCount.

Here is a working fiddle.

https://jsfiddle.net/6z3cuLys/5/

Upvotes: 2

agm1984
agm1984

Reputation: 17132

Looks like you could be missing .bind() on there. Without it, this has the wrong context as it fires the function.

try

    <button onClick={this.handleClickInc.bind(this)}>{"+"}</button>
    <button onClick={this.handleClickDec.bind(this)}>{"-"}</button>

or, fat arrow functions generally do this work for you

    <button onClick={() => this.handleClickInc()}>{"+"}</button>
    <button onClick={() => this.handleClickDec()}>{"-"}</button>

Upvotes: 1

Related Questions