5

can someone explain the difference between

an anonymous function

  <button onClick={() => this.functionNameHere()}></button>

and

calling the function like below

  <button onClick={this.functionNameHere()}></button>

and also when to use either (such as different scenarios to use one over the other).

Kelvin
  • 79
  • 1
  • 1
  • 2

2 Answers2

2

The first example correctly binds the value of this (the exact problem lambdas strive to resolve in ES 2015).

 () => this.functionNameHere()

The latter uses the scoped-value of this which might not be what you expect it to be. For example:

export default class Album extends React.Component {

    constructor(props) {
        super(props);
    }

    componentDidMount ()  {
        console.log(this.props.route.appState.tracks);  // `this` is working
        axios({
            method: 'get',
            url: '/api/album/' + this.props.params.id + '/' + 'tracks/',
            headers: {
                'Authorization': 'JWT ' + sessionStorage.getItem('token')
            }
        }).then(function (response) {
            console.log(response.data);
            this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
        }).catch(function (response) {
            console.error(response);
            //sweetAlert("Oops!", response.data, "error");
        })
    }

We would need to sub in a lambda here:

.then( (response) => {
        console.log(response.data);
        this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
    } )

or bind manually:

.then(function (response) {
            console.log(response.data);
            this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
        }.bind(this) )

Examples stolen from: React this is undefined

Community
  • 1
  • 1
djthoms
  • 3,026
  • 2
  • 31
  • 56
1

In ES6, with the first scenario "this" refers to the Component where the function called belongs to. <button onClick={() => this.functionNameHere()}></button> is equivalent to <button onClick={this.functionNameHere.bind(this)}></button>.

On the other hand, in <button onClick={this.functionNameHere()}></button> "this" refers to the button itself.

I came from Python and I'm still a bit confuded about javascript context. Check this video for further info: https://www.youtube.com/watch?v=SBwoFkRjZvE&index=4&list=PLoYCgNOIyGABI011EYc-avPOsk1YsMUe_

  • if in the second example this refers to the button itself. How come when the page re-renders, the function gets called regardless? Shouldn't this.functionNameHere() be undefined then since the function was defined as a class function not a button function? – Kelvin Feb 20 '17 at 03:54