Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 646
o.O Avatar asked May 22 '26 00:05

o.O


2 Answers

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/

like image 81
Christopher Messer Avatar answered May 23 '26 12:05

Christopher Messer


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>
like image 28
agm1984 Avatar answered May 23 '26 14:05

agm1984



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!