DEV Community

Paul Michaels
Paul Michaels

Posted on

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:


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

private onMouseUp(e) {
        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.


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:


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:


But then bind the method in the constructor:

constructor(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) => {
        dragging: true

This doesn't require any binding.


The original post for this is here

Top comments (0)