Search code examples
reactjsonclicksetstate

Can't figure out why onClick is not updating state


I know there are similar questions around this issue, but I was unable to use those answers to get my code working..

I want to increment the state of nextPage by 1 every time the button is clicked.

I've tried removing the return in the handleClick Method. I also tried adding a variable to hold the updated num and pass that as the value of state like so

handleClick = (num) => {
let x = num++
        return this.setState({
            nextPage: x
        })
    }

Nothing I try seems to update state.. This is my current code below:

import React, { Component } from 'react'


class Pages extends Component {
    constructor(props) {
        super(props)
        this.state = {
            nextPage: 1
        }

    }
    handleClick = (num) => {
        return this.setState({
            nextPage: num++
        })
    }

    render() {
        return (
            <div className='pageNav'>


                <button className="nextButton" onClick={() => this.handleClick}>Next </button>

            </div>
        )
    }

}

export default Pages

Solution

  • You are not invoking handleClick when you press the button.

    onClick={() => this.handleClick}
    

    is equivalent to

    onClick={() => {
      return this.handleClick
    }}
    

    which is not the same as

    onClick={() => {
      return this.handleClick(/* do you need to pass a number here? */)
    }}
    

    or

    onClick={this.handleClick}