8 Handling events in React

 

This chapter covers

  • Reacting to user input using events
  • Handling event capturing and bubbling
  • Managing default event actions
  • Attaching event listeners directly to the DOM

Events are the way that users interact with a JavaScript web application. Events can be caused by mouse movement or clicking, touch interface clicks and drags, keyboard button presses, scrolling, copying and pasting, as well as indirect interactions such as focusing and unfocusing elements or the entire application.

So far, we’ve created React applications with very little user interaction. We’ve handled clicking a button here and there, but not really talked in depth about how the click event works, and how we as developers handle it. We’re going to change that in this chapter, which is dedicated to event handling.

You can think of events as the way to handle inputs from a user. Our web application creates JavaScript XML (JSX), which is converted to HTML. The user then interacts with that HTML, and the result of those interactions are events dispatched from the HTML elements to our React application. This simple flow of information is illustrated in figure 8.1.

8.1 Handling DOM events in React

8.1.1 Basic event handling in React

8.2 Event handlers

8.2.1 Definition of event handlers

8.2.2 Event objects

8.2.3 React event objects

8.2.4 Synthetic event object persistence

8.3 Event phases and propagation

8.3.1 How phases and propagation work in the browser

8.3.2 Handling event phases in React

8.3.3 Unusual event propagation

8.3.4 Nonbubbling DOM events

8.4 Default actions and how to prevent them

8.4.1 The default event action

sitemap