Modern web applications are interactive and dynamic or built to be. Users will be clicking around, filling out form fields and triggering numerous other events through their keyboard entries, mouse moves, thumbing around (on a touch screen, such as a smartphone or tablet) and the general reactions of the browser Window and DOM of the web pages.
In this guide, we will:
- Take a look at the events that you will usually encounter as a web developer, whether in the backend or (most often) in the frontend of the web app.
- Cover the event listeners used to "listen for"/track DOM events.
- List the matching "Reactified" DOM event listeners.
- Finally, we will cover how to handle DOM events in your React components, whether inline (within the JSX) or in an external function.
Throughout this guide, the instructions and code samples will be skewed more towards how it is done in React (and within the JSX code) though we will cover how events are traditionally-handled in plain HTML and vanilla JavaScript. So, keep that in mind as you go through this guide.
If you have questions after going through this developer guide, please, share them in the comments section at the end.
And, so, let's begin ...
1. How Events Work
So, how do events work in a web app?
Whether or not you are using React, another frontend framework or doing server-side rendering (SSR), the flow for how events work (in your web app) is as follows:
- Event Triggered: An event can be triggered by one of:
- User input in a form field. This could be an input field (for text, email, number, etc. values), a select field, textarea, etc.
- Mouse event: a user clicks, double-clicks or moves the mouse over an element in the DOM.
- Network Event: The web page loads, unloads, fails to go online, goes offline, etc.
- Or, something else ... (some of which we will cover through other sections of this guide.)
- Event Handled: Once an event gets triggered, it is the responsibility of the JavaScript code on that page to respond to the event that was emitted.
"Handling the event" refers to what the JavaScript code should do to respond to the event that was triggered.
This event handling can be done inline (right inside the HTML/JSX) or in an external function (if the event handling logic's code is more complex, uses conditionalal statements, takes more than one line of JavaScript to implement, and so on.)
We will cover some basic event handling operations (both inline and in an external function) later on in this guide.
- DOM Gets Updated: Depending on what event was triggered, how it was handled and the intended after-effect, the DOM could be updated to reflect the DOM event that just took place.
This is optional (depending on the intended user experience of the app), but recommended.
Sometimes, a DOM update may not need to happen (for example, when a user clicks on a button that is just for aesthetic, but not interactive, uses in the UI.)
In other cases, a page (i.e the DOM) may need, for instance, to print a success or error message after a user submits a form he/she was filling in.
But, in typical pre-schooler logic/reasoning, "where do events come from?"
Well, let's cover that next ...
2. On Events, Event Listeners and Event Handlers
If you have scoured the Internet for any length of of time, you would have come across articles talking about events and the various terms used to call the various aspects related to events and event handling.
Some people get the terms correctly; others just mix things up and use the terms loosely and interchangeably.
So, let's sort out these terms.
There are three things related to events and event handling in your frontend app:
- `Event`: This something that happens in your browser, window, document or an HTML (or JSX) element. This could be a click, focusing on a button or input field, a keypress or something triggered by a connection status or a WebSocket activity.
An event can come from the Window (such as being opened, closed or navigated away from), an Element on the page (such as a `<form>`, `<input>`, `<div>` or `<button>` element/tag), a Keyobard action (such as pressing a key, releasing a key, etc.) or from the Mouse or pointing device (such as a click, mouse-over, blur or drag).
Whatever the source of what just "happened", the thing that just happened is called an event in frontend terms.
- `Event Listener`: To monitor whether or when a particular event (click, keypress, etc.) happens in the DOM, you "listen" for the event.
To listen for an event, you use an HTML property known as an "event listener". This event listener will go inside the HTML element/tag that you want to monitor/listen on for a particular event.
An event listener is named by prefixing it with "on" followed by the name of the event.
So, for example, the event listener for the click event would be "onclick", the event listener for the "dragstart" event would be "ondragstart" and the event listener for the "loadstartcapture" event would be "onloadstartcapture".
This is in plain HTML and JavaScript.
In React, the event listeners are renamed to conform to JavaScript naming conventions. So, they are camelCased. It is prefixed with the "on" word and every word in the event's name will be Capitalized.
So, for example, some event names and their respective event listeners would be:
- `click` : `onClick`
- `mousemove`: `onMouseMove`
- `loadstartcapture`: `onLoadStartCapture`
In other words, to create an event listener in React, you will:
- prefix the event listener's name with "on"
- Capitalize every word in the event name. E.g `loadstartcaptue` becomes `LoadStartCapture`
- And, voila! You have an event listener to use in your React JSX code.
If in doubt about how to properly name an event listner in React, see the React Common Components and Events Reference in the official React docs.
- `Event Handler`: So, you know what an event is and how to listen for an event.
But, what do you do after you listen for an event (and that event is triggered in your DOM or Window)?
Well, you handle the event that just happened. Because that's what Frontend Engineers do. To handle an event, you use an "event handler".
An event handler is a piece of JavaScript code that serves as the logic for how to react to an event that takes place in your app.
You can handle an event inline (i.e right inside the HTML or JSX markup of your web page or component) by passing your JavaScript code to the event listener in a pair of "quotes" (if using plain HTML) or in a pair of curly {braces} if using JSX (i.e. in React).
You can also create an external JavaScript function (in an external file or inside your React component) and then reference it from your HTML/JSX markup.
We will look at examples of both types of event handlers (in the How Events are Handled in React section) later on in this guide, God willing.
To recap:
- An event is something (like a click, mousemove, form submission, etc.) that happens in your browser window, web page or React component.
- An event listener is an HTML property that is prefixed with "on" and followed by the name of the event it is monitoring/listening for.
In plain HTML, the event listener will be all lowercase (as in "oneventname"). In React, every word of the event name will be camelCased (as in "onEventName").
So, the `onmousemove` event listener (in plain HTML) will now be `onMouseMove` in your React JSX.
- An event handler is a piece of JavaScript code that determines how to react to the event that just happened in your Window or DOM. This JavaScript code could either be inline (right inside your HTML or JSX markup) or in an external JavaScript function.
3. Event Sources
The events your frontend/React app interacts with, listens for and handles could come from a number of places.
In this section, we will take a look at some of the most common sources for events in your web app.
These event sources include:
3.1: Window
This is the window or tab that's open in the browser. The `Window` can trigger events and listen to them. There are a number of categories of events that the `Window` supports.
These are:
- Clipboard Events: These check and track the status/contents of the clipboard. These are the `copy`, `cut` and `paste` events
- Connection Events: These track the status of the browser's access to the Network. These are the `offline` and `online` events.
- Device Orientation Events: These track the orientation of the device (phone, tablet or computer) based on data from the magnetometer orientation sensor. These are the `devicemotion`, `deviceorientation` and `deviceorientationabsolute` events.
- Focus Events: These track when when an element gains or loses focus. These are the `focus` and `blur` events.
3.2: Document
This is the web page that's open in a browser window or tab. What we know as the `DOM` (the Document Object Model) is actually the contents of the web page.
So, basically:
- Document: is the "container"/web page open in your browser window/tab.
- DOM = 'contents of the web page' and contained within the Document. These are the headings, paragraphs, forms, buttons, and so on that you see on the web page.
The "contents" of the web page would include such HTML elements as `<body>`, `<div>`, `<p>`, `<span>`, `<table>` and every other HTML element (derived from the HTMLElement ), which we will cover shortly) that is rendered in a web page.
The `Document` has a range of categories of events that it tracks and can handle.
These categories of events (and some of their event types) are:
- Clipboard events: (`cut`, `copy` and `paste`)
- Fullscreen events: (`fullscreenchange`, `fullscreenerror`)
- Load and unload events: (`DOMContentLoaded` && `readystatechange`)
- Pointer lock events: (`pointerlockchange`, `pointerlockerror`)
- Scroll events: (`scroll`, `scrollend`)
- Selection events: (`selectionchange`)
3.3: Element
This is the abstract base "Element" from which all other elements in your DOM inherit. A look at the
`Element` documentation will list all the events supported by all child elements (such as the `HTMLElement`, `HTMLFormElement`, etc.)
The DOM `Element` supports all types of events, including:
- Clipboard events
- Animation events
- Composition events
- Fullscreen events
- Focus events
- Keyboard Events
- Mouse events
- Pointer events
- Transition events; and
- Touch events
You can see detailed coverage of each of these events in the
Element Events documentation on the Mozilla Developer Network site.
In the following sections, we will cover some of these categories of events as they relate to specific sub-elements of the DOM `Element`.
3.4: HTMLElement
This is representative of any HTML element (i.e tag) that you can find in your HTML markup. In React, this would be the tags/elements of your component's JSX markup.
These include your `<body>`, `<div>`, `<p>`, `<span>`, and other elements/tags.
It doesn't matter if an element is an inline tag (such as `<span>`, `<i>`, etc.) or block element/tag (such as the header tags (`h1` - `h6`), `<p>`, `<div>`, etc.). Like the
`Window` and
`Document` objects, your HTML elements/tags can trigger events.
An `HTMLElement` can trigger general events like: `cancel` (used with the `<input />` and `<dialog>` elements), `change` (for when the value of a form input field, such as `<input/>`, `<select>` and `<textarea>`) changes), `error` (for when a resource does not load) and `load` (for when a resource successfully-loads).
Any `HTMLElement` can also trigger:
- Clipboard events: (`cut`, `copy`, `paste`)
- Popover Events: (`beforetoggle`, `toggle`)
- Drag-and-Drop Events: (`drag`, `dragend`, `dragenter`, `dragleave`, `dragover`, `dragstart`, `drop`)
- Mouse Events: (`click`, `dblclick`, `mousedown`, `mouseenter`, `mouseleave`, `mousemove`, `mouseout`, `mouseover`, etc.)
- Focus Events: (`focus`, `blur`, `focusin`, `focusout`)
- Keyboard Events: (`keydown`, `keypress`, `keyup`)
The `HTMLElement` also i
nherits and supports all the event types of its (abstract) base/parent
`Element` class such the Fullscreen events, Touch events (if the web app is being viewed on a phone or tablet device), Pointer events, Transition events (to track, trigger and react to CSS transition events in the DOM), etc.
Please, see the
`Element` Class Events for a full list of the events supported by the `HTMLElement` (and any other sub-class of `Element`, such as the `HTMLFormElement` element, which we will cover next.)
3.5: HTMLFormElement
This represents a `<form>` element on the web page. Its `HTMLFormElement.elements` property represents a collection of all the controls (i.e. fields: <`<input>`, `<select>`, `<textarea>`, etc.) on the form.
The `HTMLFormElement` supports these (form-exclusive) events:
- `reset`: For when the form is cleared/reset
- `formdata`: For after the user-entered form's data (i.e. `formdata`) is collected into a list (and ready to be submitted)
- `submit`: For when a user hits the "submit" button
As a child of the base `Element` class and the parent `HTMLElement` class, the `HTMLFormElement` also, by extension, supports all the events available in those two parent elements.
So, you can handle `focus`, `copy`, `mousedown`, `keypress` and other events when creating the logic for your form.
3.6: HTMLInputElement
This represents the input elements on a form in the DOM.
These are:
- `<input>`: Irrespective of the input "type" property ("search", "text", "email", "password", "number", "checkbox", "radio", "color", "file", etc.)
- `<select>`: Whether "multiple" options can be selected or not.
The `HTMLInputElement`(and its child tags, listed above) support input-handling events including:
- `invalid`: If the input fails validation
- `select`:
- `search`: On an `<input type='search'>` element; when the search is initiated.
- `selectionchange`: When the text selection has changed in an `<input />` element.
3.7: XMLHttpRequest
These are events that are triggered when you try to fetch (or interact with) data over HTTP (via an API tool like
`fetch()`,
axios-http or directly using the `XMLHttpRequest` object.
The XMLHttpRequest-related events include:
- `abort`
- `error`
- `load`
- `loadstart`
- `loadend`
- `progress`
- `readystatechange`
- `timeout`
For a more detailed coverage, please, see the XMLHttpRequest Events documentation on MDN.
3.8: Web Media
These are the Web APIs related to the consumption of audio and video media in your web app.
If you are building an app that also supports playing videos, recording media (audio or video or your screen) or streams media to your users, then your app will need to listen for and handle events related to working with media in your React components.
These Web Media APIs include the:
For details of the events supported by each Media API, please, see their respective
links above.
3.9: WebSocket
If your React app uses the
WebSocket API, then your app needs to listen for and handle events related to making WebSocket connections in your app.
Some of the Events supported by the WebSocket API include:
- `open`: For when a WebSocket connection is opened.
- `close`: For when the connection with the WebSocket is closed.
- `error`: When there was an error establishing a connection with the WebSocket.
- `message`: For when a message is received via a WebSocket connection.
3.10: WebRTC
These are events that are triggered while your web app client tries to communicate with other clients using the
WebRTC API.
So, if you have used Zoom, Google Hangouts and the like, the web app you were communicating on would have emitted these RTC ("real-time communication") events. WebRTC eventsinclude: `RTCDataChannel`, `RTCDTMFSender`, `RTCIceTransport`, `RTCPeerConnection`.
Some of the events emitted by (and listened for by) the WebRTC API include:
- `open`: A new RTCDataChannel has been opened (or re-opened) successfully.
- `datachannel`: When a new RTCDataChannel connection has been opened/established.
- `closing`: To indicate that the RTCDataChannel (and its underlying data transport) is preparing to close.
- `close`: To indicate that the RTCDataChannel (and its underlying data transport) has successfully-closed.
- `message`: When a message has been received on the RTCDataChannel.
- `error`: To indicate that an error has occured with either the RTCDataChannel or the RTCDtlsTransport system.
- `connectionstatechange`: When the state of the RTC connection has changed.
- ... and more.
Please, see the "Events" section of the
WebRTC API documentation for a more comprehensive list and coverage of the events supported by and/or emitted by the WebRTC API and its interfaces.
3.11: NetworkInformation
These are events that are triggered and/or emitted when your app/(browser client) tries to connect to the Internet (or your local network).
It supports all the events from the base Event object and an additional `change` event (for when the connection state changes.)
3.12: Payments API
These are events that are connected to when your app requests/initiates a request for a payment (from the app user) or responds to a payment request.
4. Reactifying DOM Events and Listeners
In regular HTML:
- your events are all lowercase (such as "mousemove", "change", etc.) even if an event's name is composed of more than one word (such as "beforetoggle", "dragstart", and so on.)
- the event listeners are prefixed with "on" followed by the name of the event, which is why you have "onclick", "onsubmit", "onfocus", and so on. So, for example, you will have: `<button type="button" onclick="getFormInfo();">Info</button>`
In JSX (which is an extended form of JavaScript used to write and wrap HTML), you need to make your event names and names of event handlers more JavaScript-friendly and JavaScript-like.
This is something you should keep in mind as you develop your React components.
So, in JSX:
- your events are lowercased whether the event's name is a single word (like `change`, `focus`, `click`), made up of two words (such as `dblclick`, `mousemove`, `dragstart`, `keyup`, etc.) or multiple words (such as `mousemovecapture`, `canplaythrough`, etc.)
- your event listeners are prefixed with `on` and camelCased. Each word in the event listener's name is Capitalized.
So, you will have event listeners like: `onSubmit`, `onClick`, `onChange`, `onSelect`, `onMouseMove`, `onMouseMoveCapture`, `onCanPlayThrough`, etc.)
5. Most Common Events and their Event Listeners
Below is a list of some of the most common events (e.g. `click`), their HTML event listeners (prefixed with "on"; e.g. `onclick`) and their JSX/React event listener equivalents (prefixed with "on" and camelCased; e.g. `onClick`).
I have decided to focus on the most common event types you will encounter as a frontend developer, irrespective of what type of React app you are building: mouse events, keyboard events, touch events and form events.
As you develop your React app's components, most of the time you will be concerned with events from the following sources (irrespective of the type of app your are building).
Without much ado, these event sources are:
6. Mouse Events
These are DOM events that come from the interaction that your pointing device (such as your computer mouse) has with the web page and its contents.
These include such events as: `mouseover`, `mouseout`, `mousedown`, `mouseup`, `click`, `dblclick`, etc.
The `click` event is one of the most tracked on any web app. Depending on the nature of your app, you may also need to listen for and handle other mouse-related events.
These mouse events are:
Event |
HTML Event Listener |
React JSX Event Listener |
click |
onclick |
onClick |
dblclick |
ondblclick |
OnDblClick |
mousedown |
onmousedown |
onMouseDown |
mouseup |
onmouseup |
onMouseUp |
mouseout |
onmouseout |
onMouseOut |
mousemove |
onmousemove |
onMouseMove |
mouseover |
onmouseover |
onMouseOver |
drag |
ondrag |
onDrag |
dragstart |
ondragstart |
onDragStart |
dragend |
ondragend |
onDragEnd |
dragenter |
ondragenter |
onDragEnter |
dragleave |
ondragleave |
onDragLeave |
dragover |
ondragover |
onDragOver |
drop |
ondrop |
onDrop |
7. Keyboard Events
These are events that come from your web app user's use of the keyboard to interact with your web app through data entry, etc.
You can handle these events when doing form input tracking and validation. Or if you are handling user search on your site. Or if you are developing an input-tensive app (such as a program to train users to type faster or correctly, etc.)
The keyboard-specific events you will need to listen for and handle in your React components (and their respective event listeners) are:
Event |
HTML Event Listener |
React/JSX Event Listener |
keydown |
onkeydown |
onKeyDown |
keypress |
onkeypress |
onKeyPress |
keyup |
onkeyup |
onKeyUp |
8. Touch Events
The Touch Events come from your user's interaction with your web app in the browser of a mobile device, such as a smartphone or a tablet.
If you have a mobile-optimized web app running on a mobile browser, these events will be emitted and you may need to write some JavaScript code to handle them.
Some of these touch events include:
Event |
HTML Event Listener |
React/JSX Event Listener |
touchstart |
ontouchstart |
onTouchStart |
touchend |
ontouchend |
onTouchEnd |
touchenter |
ontouchenter |
onTouchEnter |
touchleave |
ontouchleave |
onTouchLeave |
touchmove |
ontouchmove |
onTouchMove |
touchcancel |
ontouchcancel |
onTouchCancel |
Window
9. Form Events
These are a part of either the keyboard or mouse events. I have put these here to shed special light/add focus as related to frontend/React's form processing and event handling logic.
These form-related events are:
Event |
HTML Event Listener |
React/JSX Event Listener |
change |
onchange |
onChange |
select |
onselect |
onSelect |
submit |
onsubmit |
onSubmit |
reset |
onreset |
onReset |
focus |
onfocus |
onFocus |
blur |
onblur |
onBlur |
10. The `Event` Object
No matter what source triggered an event or the event type that was triggered/emitted, an `Event` object is created in the DOM. You can use `console.log(event)` to see the API (objects, methods, etc.) of the Event object.
Throughout this guide, we have seen many types of events (and the list of events under each type) as well as how to handle them.
From a technical/programmatic perspective, an event that happens on a web page is represented as an `Event` class. This (JavaScript) `Event` class has sub-classes (aka "interfaces") which inherit from the main/parent `Event` class.
As a result, any of the child classes (or "interfaces", as they are called) also inherits the properties and methods of the main `Event` object.
In this section, we will cover some of the properties and methods of the `Event` object and how you can use some of them in your React components' code.
11. Common Event Sub-Classes/Interfaces
Some of the most common child classes (aka "interfaces") of the Event object you wlll encounter as a Frontend/React Developer will include:
- `MouseEvent`: This represents the events that happen due to a mouse movement on the page. It includes the `click`, `mousedown` and similar events covered in the Mouse Events section of this guide.
You can read more detailed coverage about the MouseEvent interface on the MouseEvent interface docs on MDN.
- `KeyboardEvent`: This represents events that are triggered due to a web page user's interaction with the keyboard.
See the Keyboard Events section for the list and the KeyboardEvent interface docs on MDN for a more detailed technical coverage of it.
- `ClipboardEvent`: This interface represents the events that are tied to your clipboard, such as `copy`, `cut` and `paste`.
You can dive deeper into the details of the ClipboardEvent interface in the MDN docs.
- `FocusEvent`: This represents the events that deal with focusing on and off an element in the DOM. The `focus` and `blur` events fall under this.
See the FocusEvent docs for more details, if you need to.
- `SubmitEvent`: This is the `submit` event that is emitted when an HTML/JSX form is submitted.
The SubmitEvent docs has more details about this event interface.
- `TouchEvent`: This interface represents the events that are emitted when your user interacts with your web app on a touch-enabled device like a smartphone or a tablet.
The TouchEvent interface docs has more details, if you want to learn more about it.
There are other child classes/interfaces of the `Event` object that you can learn more about on the
Event API docs page of MDN.
12. The `EventTarget` Object
When an event is emitted (whether in the Window, Document or an HTML Element) in your web app, the object that triggered the event is called the "Event Target."
So, `EventTarget` is the JavaScript class that represents the object (`Window`, `Document` or `Element`) that triggered the event.
The `EventTarget` will have all the properties of the target object that it represents.
So, for example, if an event is triggered in a `<button>` element, then the `EventTarget` (accessed as the `event.target` property of an event) will have all the properties (and attributes?) of the target `<button>` element, such as its style, id, tagName, innerHTML, etc.
The `EventTarget` object also has other properties and methods of it own, irrespective of the actual Element that triggered the event.
Some of the most common properties of an `EventTarget` will include, among others:
- `tagName`: This is the name of the HTML tag that is the current element. This could be "BUTTON", "SPAN", "DIV" and so on, depending on the name of the HTML tag.
- `textContent`: which is the actual text that is in the element (or between the opening and closing tags of the element, if the element is not a self-closing element).
- `style`: A reference to the element's CSS styles
- `innerHTML`
- `innerText`
- `id`: if available
- `children`: a collection of the HTML elements under the target element.
- `className`: which represents the CSS class name of the element.
- `value`: In your React component (and while working with forms), this is the value of the user input (in a `<textarea />` or `<input />` element) or selection (in a `<select>` element). Usually, you can access this using the `event.target.value` property.
- ... and a few dozen other properties that the `EventTarget` object can have depending on what properties the actual target element has.
Each of the properties of the `EventTarget` object can be accessed from your JavaScript code using `event.target.propertyName` where `propertyName` is the property you want to access.
So, you can pull out `event.target.tagName`, `event.target.id`, `event.target.value`, and so on.
The `EventTarget` is the JavaScript class that represents the object that triggered the event. As a property of the `Event` class, the `EventTarget` is simply referenced as either:
- `event.target`: To point to the target object that triggered the event. Its properties (that you will often need to work with in your React components) include:
- `EventTarget.value`: This is referred to as `event.target.value` in your frontend code.
- `event.currentTarget`.
13. Event Properties and Methods
Here are some of the most important/relevant parts of the Event object to you as a Frontend Developer.
Attributes/Properties:
- `event.target`:. This is a reference to the actual HTML tag/element that triggered the event. It is the `<button>`, `<input />`, `<p>` tags in your DOM. It is the `EventTarget` object that we covered earlier.
You can dive deeper into its API at https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
One of the most common properties of `event.target` property that you will be accessing when building forms in your React components is the `event.target.value` which represents the value of a form field.
Usually, you will use this `event.target.value` property to set the value of a piece of the component's local state (related to the form fields) as well as to formulate the object to submit to your backend API server (after successful form validation).
Methods:
- `event.preventDefault()`: This method prevents executing the default behavior of the event. For instance, when called after a form `submit` event, it prevents submitting the form data to the current page/url (which is the "default" behavior of the `submit` event).
You can then write code logic to decide how to handle the event instead (such as formulating a JSONified JavaScript object to submit to your backend API server somewhere.)
- `event.stopImmediatePropagation()`: This stops the other similar event listeners from being called (which, by extension, stops their event handlers from being executed.)
For instance, you may have more than one `onclick` event listener on a button element. If you call `event.stopImmediatePropagation()` in one of the attached event handlers, none of the other event listeners on the button element will be triggered after that.
In essence, this stops all other similar event listeners on the same element or other elements that will, of necessity, be traversed as the `click` event propagates through the DOM.
Here is a simple example:
<button onClick={getUserInfo} onClick={getUserPreferences} onClick={getUserPhotos}> Get User Data </button>
Now, let's call `event.stopImmediatePropagation()` in the `getUserInfo()` event handler function.
function getUserInfo(e){
e.stopImmediatePropagation()
// This now stops the event listeners for the `getUserPreferences()`
// and `getUserPhotos()` handlers from propagating in the DOM
// 1. Make an API call to get the user data
// 2. Make another API call to get the user's preferences
// 3. Make a third API call to get the user's photos
}
For more indepth reading of the `Event` object, please, see the more comprehensive
Event API documentation in the Mozilla Developer Network docs.
Browser Event Names
"Built-in components like <button> and <div> only support browser event names like "click". However, when you’re building your own components, you can name their event handler props any way that you like.
By convention, event handler props should start with on, followed by a capital letter.
For example, the Button component’s onClick prop could have been called onSmash"
14. How Events are Handled in React
In HTML (NOT React JSX):
- you bind an event listener to an event handler function like this:
<button onclick="handleButtonClick()"> Click Me! </button>
by passing in the event handler function in a pair of "quotes". Of course, you would have defined this `handleButtonClick()` function in a `<script>` tag inside the current HTML file or referenced a JavaScript file where this function is defined.
In JSX (NOT in HTML):
- your event handler (whether inline or an external function) is passed to the event listener in a pair of single curly `{}` braces.
If using an external function as the event handler, pass in the name of the event handler function WITHOUT the `()` parentheses. Like this:
<button onClick={handleButtonClick}> Click Me! </button>
DON'T pass in the function with the parentheses (like `handleButtonClick()`). If you do this, you will immediately invoke the event handler the moment the component mounts (i.e is loaded in the DOM).
If you are passing in the event handler code inline (i.e. written within the JSX markup), you can do that like this:
<button onClick={() => alert("You clicked me!")}> Click Me! </button>
Depending on the type of app you are building and the needs of your users, you can have cases where you are either:
- Listening for and handling multiple (different) events on the same HTML element; OR
- Listening for and handling multiple instances of the same event on the same element.
Let's take a look at how to do both, with some code samples.
14.1 Listening for and Handling Multiple Events on the Same Element
You may have an element (a `<div>`, `<input/>`, `<button>`, etc.) that listens for and handles more than one type of event on the same element.
For example, you may have a button that reacts to both a click event and a mouseover event. Each of these two (or more) events would have its own event listener that calls its related event handler (whether inline or in an external function) to do what is needed to handle the event that just occured on the element.
A simple example of these would be:
<button onClick={handleClick} onMouseOver={changeColor}> Test Me </button>
In this example:
- when a user moves his/her mouse over the button, the `onMouseOver` event listener calls the `changeColor()` event listener (function) which (judging by the name of the event handler) will change the color of the button or its text (depending on the logic implemented inside the `changeColor` event handler.)
- when a user clicks on the button, the `onClick` event listener calls the `handleClick()` event handler (function) which does something (depending on the developer's coded logic) that reacts to/handles the click event on the button.
You could have multiple events (and event listeners) on the same element depending on the needs of your application, user experience and logic.
Just make sure that each event on the element will have its own event listener that calls an event handler (whether inline in an external function), just like we did in this code sample.
Just use them wisely and don't unnecessarily convolute your React components by trying to play "smart" with it. Be practical, name your event handlers appropriately and keep your code as simple as it can get. That's all! :)
14.2 Multiple Instances of the Same Event on a Single Element
The other scenario is when you need to do more than one thing to handle the same event on the same element.
For example, you may be building a chat application and have a button that the user clicks on to start a chat session. But you also want to notify other users in the same chatroom that userA has started a chat session.
You could handle both pieces of logic in the same event handler, but sometimes it is cleaner to just have two different event handlers (each bound to a different `onClick` listener) on the same element.
A simple example of this would look like:
<button onClick={startChatSession} onClick={notifyParticipants}> Start Chat </button>
In plain HTML and JavaScript, you would have implemented this like this:
<button onclick="startChatSession()" onclick="notifyParticipants()"> Start Chat </button>
Then, in your HTML file's `<script>` tag (if using plain HTML and vanilla JavaScript) or in the body of your React component, you can define the event handlers like this:
function startChatSession(){
// handle click logic
console.log("Start a WebRTC chat session.")
// In real life, you would use the WebRTC API to start a chat session
}
function notifyParticipants(){
// handle focus logic here.
console.log("Call an API to send a message to each participant.")
// In real life, you would call an endpoint on your backend API server
// to notify the current user's friends to join the chat.
}
You could also listen for and handle these events inline (i.e. right inside the HTML or JSX markup), like this:
1. In plain HTML and vanilla JavaScript:
<button
onclick="console.log('You clicked me!')"
onfocus="alert('Hey, you focused on me.');"
> Let's Interact
</button>
2. Or, In React:
<button
onClick={(e) => console.log(`You clicked on the ${e.currentTarget.tagName} tag!`)}
onFocus={() => alert('Hey, you focused on me.')}
> Click Me </button>
15. Manually Listening for and Handling Events
In the preceding examples, we saw how to listen for an event emitted on an element using the appropriate event listeners (or the "Reactified" camelCased equivalents).
But, you can also manually listen for an event on element (or stop listening for an element) using one of two DOM element functions:
- `addEventListener()`: definition. signature. Example
- `removeEventListener()`: definition. signature. Example
May do these manually inside an event handler, for example, to attach this event listener to an element on the page (from then on) or remove an existing event listener from an element from then onwards.
16. React Native Events
When developing a native mobile app (whether it runs on iOS, Android or another Operating System), the native app will emit some events.
If you are developing your native mobile app using the React Native framework, your app will emit events that you would need to handle.
Some great resources for learning about the events you will encounter and need to handle (when building native mobile apps using React Native) include:
17. Best Practices for Handling Events in React
Here are some "rules of thumb" for when you are working with events in your React components.
- Handle simple event logic inline: If all you need to do is set your component's (local) state to the new value of an input element, for example, you can do that as a one-liner inline. You won't need to define an external function just to call `setFirstName(e.target.value)`, for example.
- Move complex event handling logic to an external function: If your event handling logic needs more than a few lines of JavaScript to implement cleanly, please, use an external function.
For example, once a user clicks on the `submit` button of your form, you want to collect the values entered into the various form fields into a JavaScript object, JSONify it and then make a call to your backend API server to submit the form data.
That's more than you want to put in an inline event handler. Settle for simplicity and cleanliness and opt for an external function.
- Use one event handler per event: Unless you have a very good and practical reason for not doing so, use one event handler to handle the logic for only one event.
And, that applies even if you are listening for multiple instances of the same event on a single element. Or, even if you are listening for different event types on the same element.
Keep the logic for only one event in an event handler. Don't create a code smell just because you want to "conserve" lines of code in your React app. Trust me, it won't be worth it.
- Name your event handlers logically and unambiguously: As you read more and more codebases of developers, you will start wondering how they passed the "code review" process (if any) at their company.
Name your external event handler function clearly.
Will the event handler be taking care of submitting the form, call the function `handleFormSubmit`.
Does a button trigger the download of new stock prices when clicked on? DON'T call it `handleClick()`; instead call it the `downloadNewStockPrices()` function. And, so on.
Does a function handle reacting to changes in the blog title? You can call the event handler `handleTitleChange()`, but not just `handleChange()` (which would be ambiguous, since we don't know if that handles changes to the blog post's title or the body of the blog post.)
Name your event handlers such that your fellow developers (and future ones lucky enough to be charged with updating and maintaining your codebase) won't need a cheatsheet for what function handles which event in your component.
Make a developer's life easy and save them some embarrasment on that daily "Sprint Call".
- Don't make your event handlers namesakes of your built-in event listeners.
Developers can get very lazy and very uncreative sometimes. Some go as far naming the event handler function after the event listener. So, they would name the event handler for the `click` event as `onClick()`.
To a newbie developer, they may not know if the `onClick` property on that `<button onClick={onClick}>` is the event listener or so-named because the (event handling) function it is referencing is so-named.
Be a little creative with your naming conventions so that less-experienced devs have fewer opportunities to mess up or mis-learn proper coding etiquettes.
There are more best practices for handling events in your React app. But, you will collect them as you develop more React apps and handle more event logic in your components.
18. Technical Reference