0

this is defined in the render method, but not in an eventHandler that calls an arrow function.

I did a fresh clean slate of npx create-react-app projectName and am reproducing an unexpected issue I'm encountering in a personal project.

import React from 'react';

class RemoteSubmitButton extends React.Component {
  onSignUpClick = () => {
    debugger; // "this" is undefined
  };

  render() {
    debugger; // "this" is defined
    return (
      <button
        type="button"
        onClick={this.onSignUpClick}
      >
        Submit
      </button>
    );
  }
}

export default RemoteSubmitButton;

Whenever I reference this inside of an arrow function, I expect the context of the calling method (the render method) to get carried over. Placing a few debuggers I see that this is defined in the render method, but not within the onSignUpClick method.

DarkKunai99
  • 105
  • 1
  • 4
  • 13
  • 2
    Are you trying to access `this` in console while debugger stops execution and you get reference error or you are accessing it using `console.log(this)` ? – Zohaib Ijaz May 12 '19 at 18:07
  • The former. Latter seems to be working fine. Is the implication here that the context does get carried over, but debugging a binded method in the console problematic? How would I best debug contexts like these? – DarkKunai99 May 12 '19 at 18:18

1 Answers1

1

Using fat arrow functions transpiles code in such a way that there is no guaranteed way of knowing what variable encapsulates the scoped context. A workaround that works is using manual binding in class properties:

import React from 'react';

class RemoteSubmitButton extends React.Component {
  constructor(props) {
    super(props)
    this.onSignUpClick = this.onSignUpClick.bind(this)
  }

  onSignUpClick() {
    debugger; // "this" is defined
  };

  render() {
    debugger; // "this" is defined
    return (
      <button
        type="button"
        onClick={this.onSignUpClick}
      >
        Submit
      </button>
    );
  }
}

export default RemoteSubmitButton;

DarkKunai99
  • 105
  • 1
  • 4
  • 13