Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use anonymous functions in JSX

Tags:

reactjs

jsx

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).

like image 254
Kelvin Avatar asked Oct 30 '22 11:10

Kelvin


1 Answers

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

like image 196
djthoms Avatar answered Nov 27 '22 14:11

djthoms