How to access React instance inside the event handler

How to access React instance inside the event handler

Consider the below React component

import React, { Component } from 'react';

class Test extends Component{
    someFunction(){
       console.log('somefunction called');
    }

    render(){
        return(
         <button onclick={this.someFunction}>Console Log</button>
    )}
}

If you try to call this.someFunction will be undefined. This can be solved in two ways

Using bind functions

By using bind, the function someFunction is binded to the instance of class and can be accessed using this

import React, { Component } from 'react';

class Test extends Component{
    constructor(){
       this.someFunction = this.someFunction.bind(this);
    }
    someFunction(){
       console.log('somefunction called');
    }

    render(){
        return(
         <button onclick={this.someFunction}>Console Log</button>
    )}
}

Using arrow functions

We can also use arrow functions and avoid using bind.

import React, { Component } from 'react';

class Test extends Component{
    someFunction = () => {
       console.log('somefunction called');
    }

    render(){
        return(
         <button onclick={this.someFunction}>Console Log</button>
    )}
}

Difference between bind and arrow function

Although bind and arrow function can be used to achieve the above objective, both are different in nature. Bind function, as the name suggests, binds the function with the class prototype. Arrow functions are not bound to the class instance. Here is an example.

When using bind method to bind the someFunction with the class, it will be defined in prototype of Test class.

console.log(Test.prototype.someFunction) // defined

When using arrow function for someFunction, it will not be defined in the prototype of Test class.

console.log(Test.prototype.someFunction) // undefined
%d bloggers like this: