DEV Community

Paul Michaels
Paul Michaels

Posted on

2 1

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

The original post for this is here

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay