0

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"

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Oh I see. this goes too even if I am not passing a value? something like a just toggle (true/false) function ?
@DarkProfessor If you call the function instead of passing it as a callback - then yes. onClick={fn} - ok onClick={fn()} - not ok unless fn returns a new function :)
This becomes redundant if you are using arrow functions in render. If you need to create multiple togglePage callbacks with different values you could rewrite your code by creating makePageToggler(currentpage){ return () => this.setState({ currentpage })} and the call it onClick={this.makePageToggler(2)}
You don't. That statement, as the function name bind() suggests, is used to bind the name togglePage of the context this to the function togglePage you implemented. Though, you can write that function in this way: togglePage = (page) => { ... }, and you will not need nay binding
Notice in case of makePageToggler it is ok to make a call because it returns a new function.
|
0

one more approach would be to not bind it in constructor,instead bind it in the button tag as shown below,

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.