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

class SayHello extends React.Component {
    constructor(props) {
        super(props);
        this.state = { message: 'Hello!' };
        // This line is important!
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        console.log(this.state.message);
    }

    render() {
        return <button onClick={this.handleClick}>Say hello</button>;
    }
}

export default SayHello;`

why do we need to bind ?? I understand the context but wont this will refer to the instance, can someone explain with an example in a non-react way or in simple JS class.

Nish
  • 353
  • 3
  • 9
  • `this` will actually refer to the React.Component class. And since that one merelly has the state as a instance variable and not with your own data, you need to point the handler that mutates it to the correct instance. – Rafael Rocha Jun 15 '20 at 07:43
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind – Dennis Vash Jun 15 '20 at 07:49
  • 1
    I always use arrow functions to avoid the hassle of binding functions to this. – spaceSentinel Jun 15 '20 at 07:53
  • Here is a simple example: `var obj = {foo: 42, bar() { console.log(this.foo); }}; var func = obj.bar; func();` vs `var func = obj.bar.bind(obj); func();`. See also [How to access the correct `this` inside a callback?](https://stackoverflow.com/q/20279484/218196) – Felix Kling Jun 15 '20 at 08:13

0 Answers0