7Events
Events, and the functions that run in response to events, are what make React reactive. In this chapter, you'll learn:
- How and where to use event listeners.
- The difference between native events and SyntheticEvents.
- How to write event handlers in class and function components.
- How to use the
Event
object. - How to bind functions to class components.
- How to pass data to event handlers.
- How to use arrow functions for inline event handlers.
- How passing functions to child components works.
HOW EVENTS WORK IN REACT
To put it simply, listening for events in a React component and handling events is done similarly to how HTML event attributes trigger actions in a browser.
In HTML, it's possible to use event attributes to call JavaScript functions. These event attributes have names starting with “on” and they take a function call as their value. For example, the HTML onsubmit
event attribute can be used with the <form>
element to invoke a function when the form is submitted. Listing 7-1 shows an example of using the HTML onsubmit
attribute. This example assumes that a JavaScript function named validate
()
has been defined or imported elsewhere in the HTML file.
Because HTML event attributes violate the “separation of concerns” rule that says markup and scripts should be kept separate, ...
Get Beginning ReactJS Foundations Building User Interfaces with ReactJS now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.