Huuums
Huuums

Reputation: 107

Onclick won't bind value of variable at point of rendering

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!

Upvotes: 1

Views: 59

Answers (2)

robbymurphy
robbymurphy

Reputation: 741

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.

Upvotes: 2

Manmeet S. Oberoi
Manmeet S. Oberoi

Reputation: 1122

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.

Upvotes: 0

Related Questions