0

I have a React class that functions correctly when written as such:

const LoginContainer = React.createClass({
  authenticate: () => {
      console.log('TODO: Finish authenticating');
  },

  render: function() {
      return (
        <Login authenticate={this.authenticate} />
      );
    }
});

To conform to the style guide we are using, I should use the arrow shorthand for render:

render: () =>
  (
    <Login authenticate={ this.authenticate } />
  ),

However, as soon as I rewrite this, I get

Uncaught TypeError: Cannot read property 'authenticate' of undefined

How can I get a reference to authenticate within my arrow function?

Please note that I understand the value of this is scoped differently in an arrow function, but what I'm trying to figure out is how to get the binding correct within a React class. This may be more of a React question than vanilla JS.

Mister Epic
  • 16,295
  • 13
  • 76
  • 147
  • Give this a shot: ` this.authenticate() } />` – lux Apr 05 '16 at 18:59
  • Possible duplicate of [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch) – Mike Cluck Apr 05 '16 at 19:02
  • @MikeC Added clarification. – Mister Epic Apr 05 '16 at 19:08
  • @MisterEpic The problem is still the same. Arrow functions explicitly set `this` but you need `this` to be correctly set. Why not just use standard method syntax? `render() { return (); }` – Mike Cluck Apr 05 '16 at 19:10
  • @MikeC Style conformance for an existing codebase where linting indicates a preference for the shorthand arrow. – Mister Epic Apr 05 '16 at 19:14
  • @lux Your syntax does indeed work. – Mister Epic Apr 05 '16 at 19:15

1 Answers1

1

Arrow functions lexically binds context so that this refers to the context of the outer scope.

madox2
  • 49,493
  • 17
  • 99
  • 99