DEV Community

Maksim
Maksim

Posted on

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>

And the React version

<button onClick={activateLasers}>
  Activate Lasers
</button>

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

Top comments (0)