0

In a web browser at this address: https://www.w3schools.com/js/tryit.asp?filename=tryjs_arrow_function6 , I deleted the original code, and pasted this code:

<!DOCTYPE html>
<html>
<body>



<button id="btn">Click Me!</button>

<p id="demo"></p>

<script>


document.getElementById("btn").addEventListener("click", function() {
console.log(this) // **THIS LINE GAVE THE VALUE OF AS BUTTON**

});
</script>

</body>
</html>

In React Stackblitz a tried this code:

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

class Foo extends React.Component{

  render(){
      return (
      <button type="button" onClick={function handleClick(event){
    console.log(this); // **THIS LINE GAVE THE VALUE AS UNDEFINED**
  }}>
        Click Me
      </button>
    );
  }
} 

render(<Foo />, document.getElementById('root'));

Why are the two results different? Please refer to the comments of both code samples. The first code logged to the console the button as the value of this, the second code logged to the console undefined as the value of this. Shouldn't they be the same? Why are they different?

marco-a
  • 4,996
  • 1
  • 15
  • 41
pemberton
  • 11
  • 1
  • Does this answer your question? [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Emile Bergeron May 18 '20 at 22:10
  • Also, see: [“this” is undefined inside a component function](https://stackoverflow.com/q/33973648/1218980) and [How to access the correct `this` inside a callback?](https://stackoverflow.com/q/20279484/1218980) – Emile Bergeron May 18 '20 at 22:15

2 Answers2

0

Quoting facebook react issue #5040:

class MyButton extends Component { 
   state = { tapped: false }

   tap() {
         this.setState({ tapped: true });  // --> 'this' here is undefined 
   }

   render() {
       return (
            <button onClick={ this.tap }>TAP ME</button> 
       )
   }
}

As the comment above specifies, when the tap() method got called from the button's onclick, I got an error that basically told me that 'this' is undefined.

Answer:

React.createClass auto bind this for you behind the scene.

In ES6 classes, you should bind this yourself:

<button onClick={this.tap.bind(this)}>

Emphasis mine.

Since you are using ES6 classes, the above applies: you need to bind this yourself.

Community
  • 1
  • 1
marco-a
  • 4,996
  • 1
  • 15
  • 41
-1

Write a constructor for your React class:

  constructor(props) {
  super(props);

  // Bind the function here
  this.handleClick = this.handleClick.bind(this);

}

You need to call super in your class before trying to use this. Check out this post that explains the use of super in a React class.

You also need to either bind your function like I showed above, or use an arrow function when you call the function.

Nick Kinlen
  • 1,115
  • 1
  • 18
  • 45