Ad

Use Of Bind When Calling A Function On OnClick Event

- 1 answer

Following is the sample code I was working on.

So basically there are two hyperlinks lets say , A and B.

I wanted when you click A, I want to console log 'You selected A', and if you select B, console log 'You selected B'.

I am confused as to why do I need to pass the parameters using bind ?

In the snippet below, console.log occurs when you click MIT but not when you click Stanford

'You clicked Stanford' is console logged as soon as I run the program and nothing happens on clicking it afterwards. 'You Clicked MIT' works perfectly on the other hand.

import React, { Component, PropTypes } from 'react';

export default class ToppersView extends Component {

  state = {
        currentSelected : 'Harvard'
  }  

  handleClick (str) {

    console.log(" You selected ",str)
  }

  render () {

      return (
         <div className = 'container'>
            <h3> University is : {this.state.currentSelected}</h3>
             <div>
              {/* Works */}
              <a onClick = {this.handleClick.bind(null,"MIT")}>#MIT</a>

              {/*Does not  work */}
              <a onClick ={this.handleClick("Stanford")}>#Stanford</a>

            </div>
            <br/> 


        </div>
        )
    }

}
Ad

Answer

this.handleClick("Stanford") calls the function right here, while this.handleClick.bind(null,"MIT") binds the context and argument and returns the function so it can be called later.

An event listener needs a reference to a function, but your handleClick method doesn't return anything, so after it's been executed there's nothing to bind to event listener. You could modify the handleClick method to return another function which would be called on click:

handleClick (str) {
   return function(){ // this function will be used as event callback
    console.log(" You selected ",str)
   }
}
// the function will be executed and the returned function called in event callback
<a onclick ={this.handleClick("Stanford")}>#Stanford</a>
Ad
source: stackoverflow.com
Ad