At first glance, it might seem like React uses regular browser events, but that's not true. React independently intercepts all events occurring in the DOM and broadcasts them to the back-end system.
Any event handler receives a SyntheticEvent
type object, a cross-browser wrapper over the native event object. Interface-wise, it's no different from the native wrapper, except that it works the same way in all browsers:
class Component extends React.Component {
onClick = (event) => {
console.log(event); // => SyntheticBaseEvent
console.log(event.type); // => "click"
}
// ...
}
SyntheticEvent
stores the original event object and provides an interface to access its properties and methods. This interface is the same for all browsers, which is convenient for development. For example, you need to override the default action (page reloading) when submitting a form:
See the Pen js_react_events_prevent_default by Hexlet (@hexlet) on CodePen.
As you can see, nothing is out of the ordinary. But in plain HTML, you can get this behavior in another way. You can return false
from the handler. It won't work in React.
We should do the same when we need to prevent an event from popping up. Only instead of preventDefault
the stopPropagation
function is called.
The course JS: DOM API said that it's preferable to use addEventListener
when working with HTML. One of the main reasons is that it allows you to attach many handlers, so many JavaScript add-ons take advantage of it.
In React, you don't need this way of working because event flow control is always explicit. No one can connect to React from the outside and attach their handlers.
The second thing that can scare developers is attaching handlers directly in JSX. It's worth remembering that JSX is JS code, not HTML. Therefore, it is not a problem. As you'll see later, this code is easy to read because everything is in one place.
React normalizes events so that they have consistent properties across browsers. In addition, forms can also have the onChange
event, which does what it says and greatly simplifies our work.
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.