DEV Community

Maksim
Maksim

Posted on

2 1

Handling events in React

Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences

This is what React documentation says. But besides syntactic differences you can face the problem that handling works differently too.

Let’s take a look at the examples from the official documentation:

The HTML version

<button onclick="activateLasers()">
  Activate Lasers
</button>
Enter fullscreen mode Exit fullscreen mode

And the React version

<button onClick={activateLasers}>
  Activate Lasers
</button>
Enter fullscreen mode Exit fullscreen mode

In both cases if we click on the button, the activateLasers function would be called. With the difference in when it is going to be called.

In the HTML version activateLasers is called on the button element and in the React version activateLasers is be called on the document element.

Why does it matter?

Usually the document element is the last element in the chain of elements which participate in an event handling[1]. So you can see the situation when the click handler on an ancestor element would be fired before the click handler on an descendent element. Usually you can face this problem if you use React with another non React libraries which could listen to DOM events.

I hope this small note would be helpful and will save you a lot of headache down the line if you face this inconsistency between DOM and React event handling.

[1] - Here I’m talking about event bubbling phase

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay