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 HTML

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 have created React applications with very little user interaction. We have 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 are 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 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 Non-bubbling DOM events

8.4 Default actions and how to prevent them

8.4.1 The default event action

8.4.2 Preventing default

8.4.3 Other default events

8.5 React event objects in summary

8.6 Event handler functions from properties

8.7 Memoization of event handler functions

8.7.1 Memoizing event handler properties

8.8 Event handler generators

8.9 Listening to DOM events manually

8.9.1 Listening for window and document events

sitemap