1

I have some elements with an onclick handler, which should pass the value of the variable it had, when the elements were rendered. Unfortunately they only pass the value that the variable has at the point of clicking.

class Application extends React.Component {
   constructor(props){
      super(props)

     this.state = {
       clickedValue: 0,
       array: [1,2,3,4,5,6,7,8,9,10]
     }
    }

  changeHeadline(number){
    this.setState({clickedValue: number})
  }

  render() {
  let paginationCounter = 0; 
    return <div>
      <h1>{this.state.clickedValue}</h1>
       {
          this.state.array.map((element, index) => {
            if ((index + 1) % 2 === 0) {
              paginationCounter += 1;
              return (
                <button
                    onClick={() => this.changeHeadline(paginationCounter)}
                    >
                    {paginationCounter}
                </button>
              ) 
            }
          })
        }
      </div>;
   }
}

I also created a pen for it: https://codepen.io/anon/pen/jGKzzz My intended behavior in this pen is: The headline text should change to the number the button has on it, when the button is clicked.

I'd greatly appreciate your help. Thanks in advance!

2 Answers 2

2

Your onClick event handler should change to be bound to a new function like so:

onClick={this.changeHeadline.bind(this, paginationCounter)}

bind creates a new function that calls your changeHeadline function. The first parameter is the object that should be bound to the new function's this and the second parameter is the value to be passed in to the changeHeadline function.

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

3 Comments

If i try to bind "this" in the constructor function, then it doesn't work. Any suggestions as to why it doesn't ?
@ManmeetS.Oberoi that only resolves the issue of binding this. it does not take care of the issue in the second paragraph of your answer.
Solved the issue, thanks man, I actually thought that the arrow function takes care of the binding. That's how I always understood it at least. Might have to read more into it.
0

The problem is that you are passing the variable paginationCounter by reference instead of by value

So by the time the loop completes the value of paginationCounter is set to 5 which is passed to each 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.