Sub topic 11
Mouse, keyboard, and focus events
This chapter assumes you can write function components, attach handlers such as onClick, and use useState. It covers the three event families you will use most, and the properties on each that matter in practice.
Mouse events
Mouse handlers receive a MouseEvent. The ones you will reach for most are onClick, onDoubleClick, onMouseEnter, onMouseLeave, and onContextMenu.
Useful properties on the event:
e.clientXande.clientYgive the pointer position in the viewport.e.shiftKey,e.ctrlKey,e.altKey, ande.metaKeytell you whether a modifier key was held.e.buttontells you which button was pressed:0is the main button,1the middle, and2the secondary.
import { useState } from 'react';
function HoverCard() {
const [hovered, setHovered] = useState(false);
function handleClick(e) {
if (e.shiftKey) {
console.log('Shift-click');
}
}
return (
<div
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
onClick={handleClick}
>
{hovered ? 'Hovering' : 'Move over me'}
</div>
);
}onMouseEnter and onMouseLeave do not bubble. They fire only for the element they are attached to. onMouseOver and onMouseOut do bubble, so they also fire when the pointer moves between child elements.
Keyboard events
Keyboard handlers receive a KeyboardEvent. React supports onKeyDown and onKeyUp. Use these two. The older keypress event is deprecated, so React's onKeyPress should be avoided in new code.
Read e.key to learn which key was pressed. It holds values such as 'Enter', 'Escape', 'ArrowDown', or the typed character. Avoid the deprecated e.keyCode.
import { useState } from 'react';
function SearchBox({ onSearch }) {
const [query, setQuery] = useState('');
function handleKeyDown(e) {
if (e.key === 'Enter') {
onSearch(query);
} else if (e.key === 'Escape') {
setQuery('');
}
}
return (
<input
value={query}
onChange={e => setQuery(e.target.value)}
onKeyDown={handleKeyDown}
/>
);
}Key events go to the element that has focus. A div receives them only if it can take focus, for example with tabIndex={0}. Otherwise, attach the handler to a focusable element, or use a native listener as shown in the useEffect chapter.
Focus events
Focus handlers receive a FocusEvent. onFocus fires when an element gains focus, and onBlur fires when it loses focus. Unlike the native focus and blur events, React's versions bubble. This lets a parent detect focus anywhere inside it.
A common task is closing a group when focus leaves it entirely. Moving focus between children also fires onBlur, so check e.relatedTarget, which is the element receiving focus:
function Group({ onLeave, children }) {
function handleBlur(e) {
if (!e.currentTarget.contains(e.relatedTarget)) {
onLeave();
}
}
return (
<div onBlur={handleBlur}>
{children}
</div>
);
}Here e.currentTarget is the div that owns the handler. e.relatedTarget is null when focus leaves the page, and contains(null) returns false, so onLeave runs in that case too.
How the events relate
Common mistakes
| Mistake | Fix |
|---|---|
| Checking `e.keyCode` | Compare `e.key` to a string such as `'Enter'` |
| Using `onKeyPress` | Use `onKeyDown` or `onKeyUp` |
| Key handler on a `div` never fires | Add `tabIndex={0}` so it can take focus |
| Group closes when focus moves between its children | Check `e.relatedTarget` inside `onBlur` |
| Using `onMouseOver` for hover effects and getting repeated calls | Use `onMouseEnter` and `onMouseLeave` |
Exercise
A parent div has an onBlur handler that should run only when focus leaves the div and all its children. Why does onBlur fire too often, and which property fixes it?
Show answer
React's onBlur bubbles, so it fires whenever any child loses focus, including when focus moves to a sibling inside the same div. Check e.relatedTarget, the element gaining focus, and act only when e.currentTarget.contains(e.relatedTarget) is false.
Exercise
Write the condition inside an onKeyDown handler that runs save() only when the user presses Ctrl and S together.
Show answer
if (e.ctrlKey && e.key === 's') { e.preventDefault(); save(); }. The preventDefault call stops the browser from opening its own save dialog.