0

I was following a YouTube tutorial on eventHandling when I got confused with the implementation of this keyword.

In the code below, the this keyword inside of clickHandler function gives the value of undefined. The instructor said that it is because that's how JavaScript works. But when I searched online I found out that this keyword when used inside a function of a class, points to the object itself.

This might be a stupid question to ask but since I am new to JavaScript any help will be appreciated

class EventBind extends Component {
  constructor(props) {
    super(props);

    this.state = {
      message: "Hello",
    };
  }

  clickHandler() {
    // this.setState({
    //   message : 'Goodbye'
    // })
    console.log(this);
  }

  render() {
    return (
      <div>
        <div>{this.state.message}</div>
        <button onClick = {this.clickHandler}>Click</button>
      </div>
    );
  }
}

Prajwal
  • 63
  • 2
  • 5

1 Answers1

1

This is cause you have not bound the clickHandler to this. Try below code

class EventBind extends Component {
  constructor(props) {
    super(props);
    this.clickHandler = this.clickHandler.bind(this);
    ...

  }
  clickHandler() {
    ...
  }
  ...
  
}

See here for more info: https://reactjs.org/docs/faq-functions.html

theekshanawj
  • 485
  • 5
  • 9
  • 1
    You can use arrow functions to avoid this explicit binding. – theekshanawj Sep 15 '21 at 16:09
  • Can you clarify why binding is not necessary in this example https://www.vojtechruzicka.com/javascript-this-keyword/#in-classes. Thanks – Prajwal Sep 15 '21 at 16:19
  • @PrajwalAdhikari I believe the answer you are looking for is explained here: https://stackoverflow.com/questions/38334062/why-do-you-need-to-bind-a-function-in-a-constructor – theekshanawj Sep 16 '21 at 07:22