Search code examples
javascriptreactjssetstate

Passing Variable to setState


I am new to react. In my program, the user is asked to click on a button, and according to that button, the state is changed.

This is the rendered section:

<button onClick={this.togglePage(2)}>Click Here</button>

This is the part before:

  constructor(props) {
    super(props);
    this.togglePage = this.togglePage.bind(this);

    this.state = {
      currentpage: 1,
    };
  }
  togglePage(page) {
    this.setState({
      currentpage: page,
    });
  }

Is the way I am passing a value here correct? I am getting an error saying "Maximum Update Depth Exceeded"


Solution

  • You need to pass a function, not to call it immediatelly

     <button onClick={() => this.togglePage(2)}>Click Here</button>
    

    As currently written you call togglePage in render which causes state update and rerender blowing the call stack.