Tag Archives: TypeError: this is undefined

React Tips: 2 – Binding an Event Handler

Example code here.

When dealing with any flavour of Javascript, sooner or later, you’re going to come across the this problem. The issue being that, what this means, depends on where you are. This can be a particularly prevalent issue with React; imagine the following code:

onMouseUp={this.onMouseUp}

In onMouseUp, you might want to affect the state in some way:

private onMouseUp(e) {
    this.setState({
        dragging: false
    });

If you run this, you’ll likely get the following error:

TypeError: this is undefined

I think you’ll agree, a clearer message couldn’t be had.

Binding

The answer to the problem that I’ve so eloquently posed here, is binding. Essentially, you simply tell your local function to know about this:

onMouseUp={this.onMouseUp.bind(this)}

This does fix the problem; now the method will execute without error. However, what we are actually doing here is creating a new function every time the page is rendered. To circumvent this you can leave the original code as it was:

onMouseUp={this.onMouseUp}

But then bind the method in the constructor:

constructor(props) {
    super(props);

	this.onMouseUp = this.onMouseUp.bind(this);

As an aside, if you happen to see the following error:

Argument of type ‘this’ is not assignable to parameter of type ‘MouseEvent‘.

You’ve likely missed the .bind; for example:

this.onMouseUp = this.onMouseUp(this);

Ask me how I know!

Class Properties

Another, newer (and IMHO much cleaner), way around this is the following syntax:

onMouseDown = (e) => {
    console.log('onMouseDown');
    this.setState({
        dragging: true
    });
}

This doesn’t require any binding.

References

https://reactjs.org/docs/faq-functions.html