0

I'm trying out the new React v0.13 ES6 component classes and I've run into a problem. When I try to have a click handler within the class call a function the component has received through props it throws an error saying that this isn't defined.

import React, { Component } from 'react';

class MyComp extends Component {
  render() {
    return (
      <div>
        <input type='button' value='Fetch Data' onClick={this.handleClick} />
      </div>
    );
  }

  handleClick(evt) {
    // ...do stuff

    this.props.fetch(); // throws error: `cannot read property 'this' of undefined`
  }
}

I double-checked and I can access the props from within the render function so I know that they exist in the place that they should.

When I use the old React.createClass syntax the same code works fine so I'm wondering if I missed something. I know I can fix this easily by just binding this to the handleClick method in the render function but I'd rather not if it's something simple.

Ganonside
  • 1,329
  • 1
  • 10
  • 15
  • *"I'm wondering if I missed something"* http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding – Felix Kling Sep 02 '15 at 16:21

1 Answers1

1

Change the following line:

<input type='button' value='Fetch Data' onClick={this.handleClick} />

Into this:

<input type='button' value='Fetch Data' onClick={this.handleClick.bind(this)} />

Or add a constructor with the following:

constructor() {
  super();
  this.handleClick = this.handleClick.bind(this);
}

Or if you're using ES7 features you could look into either creating your own or using an existing autobind decorator.

On a somewhat related note: consider using the button element instead.

Community
  • 1
  • 1
jdlm
  • 6,327
  • 5
  • 29
  • 49