Sub topic 11
Mouse, keyboard, and focus events
This chapter covers the event types you will use most after onClick and onChange. It assumes you can write function components, use JSX, pass props, and call useState. It also assumes you already know that React hands each handler an event object, and that handlers receive a function reference rather than a call.
How React names its events
React exposes browser events as camelCase props: onClick, onKeyDown, onFocus. Each handler receives a SyntheticEvent. This is a wrapper around the native event with the same interface across browsers. It has target, currentTarget, preventDefault(), stopPropagation(), and nativeEvent for the underlying browser event.
The event types in this chapter fall into three families.
| Family | Common props | Typical use |
|---|---|---|
| Mouse | `onClick`, `onDoubleClick`, `onContextMenu`, `onMouseEnter`, `onMouseLeave`, `onMouseDown`, `onMouseUp`, `onMouseMove` | Buttons, hover effects, custom menus |
| Keyboard | `onKeyDown`, `onKeyUp` | Shortcuts, Enter to submit, arrow-key navigation |
| Focus | `onFocus`, `onBlur` | Validation on leave, showing hints, closing popups |
React has no onKeyPress. It is deprecated in the browser, so use onKeyDown instead.
Mouse events
Click and its relatives
onClick fires after a full press and release on the same element. onMouseDown fires at the press and onMouseUp at the release. Use the lower-level events only when you need the exact moment, such as starting a drag.
The mouse event carries useful properties:
e.clientXande.clientYgive the pointer position in the viewport.e.buttontells you which button was pressed (0is the main button).e.shiftKey,e.ctrlKey,e.altKey, ande.metaKeytell you which modifier keys were held.
import { useState } from 'react';
function Row({ label }) {
const [selected, setSelected] = useState(false);
function handleClick(e) {
if (e.shiftKey) {
console.log('Shift-click on', label);
}
setSelected(s => !s);
}
return (
<div
onClick={handleClick}
style={{ background: selected ? '#cde' : 'transparent' }}
>
{label}
</div>
);
}Clicking a plain div works with a mouse, but a keyboard user cannot reach it. For anything clickable, prefer a real <button>. It is focusable and reacts to Enter and Space with no extra code.
Enter and leave
onMouseEnter and onMouseLeave fire when the pointer enters or leaves an element. Unlike most events they do not bubble. They fire only for the element they are attached to, not for its children. This is usually what you want for hover effects.
onMouseOver and onMouseOut do bubble. Moving between a parent and its child triggers them repeatedly. This causes flicker if you use them for a simple hover state.
import { useState } from 'react';
function HoverCard() {
const [hovered, setHovered] = useState(false);
return (
<div
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
{hovered ? 'Pointer is here' : 'Hover over me'}
</div>
);
}For plain visual hover styling, CSS :hover is simpler and cheaper. Use these events when hover must change state or behavior.
Context menu and double click
onContextMenu fires on a right-click. The browser then opens its own menu. If you are building a custom menu, call e.preventDefault() to suppress the default one. onDoubleClick fires after two quick clicks. Note that onClick fires twice before it.
Mouse move
onMouseMove fires very often. Avoid calling setState with heavy re-renders on every move. If you only need the position occasionally, read e.clientX and e.clientY inside another handler such as a click.
Keyboard events
Reading the key
Keyboard handlers receive a KeyboardEvent. The property you will use most is e.key. It is a string such as 'Enter', 'Escape', 'ArrowDown', 'a', or ' ' (a space).
import { useState } from 'react';
function TodoInput({ onAdd }) {
const [text, setText] = useState('');
function handleKeyDown(e) {
if (e.key === 'Enter' && text.trim() !== '') {
onAdd(text.trim());
setText('');
} else if (e.key === 'Escape') {
setText('');
}
}
return (
<input
value={text}
onChange={e => setText(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Add a task"
/>
);
}Enter adds the task and Escape clears the field.
e.key versus e.code is a common source of confusion:
| Property | Meaning | Example for the Q key on a French keyboard |
|---|---|---|
| `e.key` | The character or named key produced, which depends on layout and modifiers | `'a'` |
| `e.code` | The physical key position, independent of layout | `'KeyQ'` |
Use e.key for actions tied to a meaning, like Escape or Enter. Use e.code for position-based controls, like WASD movement in a game.
keydown, keyup, and repeat
onKeyDown fires when the key goes down and repeats while the key is held. Check e.repeat if you want to ignore the repeats. onKeyUp fires once on release. Prefer onKeyDown for shortcuts because it feels immediate, and because you can call preventDefault() on it to cancel the key's default action.
Modifier shortcuts
Check modifiers on the event instead of tracking them yourself.
function Editor({ onSave }) {
function handleKeyDown(e) {
const isSaveCombo = (e.ctrlKey || e.metaKey) && e.key === 's';
if (isSaveCombo) {
e.preventDefault();
onSave();
}
}
return <textarea onKeyDown={handleKeyDown} />;
}metaKey is Command on macOS and the Windows key on Windows, so checking both covers each platform's usual save shortcut. Without preventDefault(), the browser would open its own "Save page" dialog.
Keyboard events need focus
A keyboard event goes to the element that has focus. A div receives no key events unless it can take focus. Adding tabIndex={0} makes it focusable. If you need a key handler on something that is not a form control, add tabIndex={0} and an appropriate role. Better still, listen on a focusable element or use a native listener for the whole window, as covered in the native listeners chapter.
Input method editors
When a user types in Chinese, Japanese, or Korean, an input method editor (IME) composes characters across several keystrokes. Pressing Enter may confirm a composition and not mean "submit". Guard against it:
function handleKeyDown(e) {
if (e.key === 'Enter' && !e.nativeEvent.isComposing) {
submit();
}
}Focus events
onFocus and onBlur
onFocus fires when an element gains focus, and onBlur fires when it loses focus. A common use is validating a field when the user leaves it.
import { useState } from 'react';
function EmailField() {
const [email, setEmail] = useState('');
const [touched, setTouched] = useState(false);
const invalid = touched && !email.includes('@');
return (
<div>
<input
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
onBlur={() => setTouched(true)}
aria-invalid={invalid}
/>
{invalid && <p>Enter a valid email address.</p>}
</div>
);
}The message appears only after the user has visited and left the field, so it does not show while they are still typing the first character.
React's focus events bubble
In the browser, native focus and blur do not bubble. React's onFocus and onBlur do bubble, because React maps them to focusin and focusout. A parent can therefore observe focus changes in any of its children.
This changes how you detect "focus left the whole group". Moving focus from one child to another still fires onBlur on the parent. To tell the cases apart, check e.relatedTarget, which is the element receiving focus (for blur) or losing it (for focus). Test whether it is still inside the parent with e.currentTarget.contains(...).
import { useState } from 'react';
function Dropdown() {
const [open, setOpen] = useState(false);
function handleBlur(e) {
if (!e.currentTarget.contains(e.relatedTarget)) {
setOpen(false);
}
}
return (
<div onBlur={handleBlur}>
<button onClick={() => setOpen(o => !o)}>Menu</button>
{open && (
<ul>
<li><button>Profile</button></li>
<li><button>Sign out</button></li>
</ul>
)}
</div>
);
}The menu closes only when focus moves outside the whole div. Tabbing from "Menu" to "Profile" keeps it open.
Common mistakes
- Using
onKeyPress. It is deprecated. UseonKeyDown. - Comparing
e.keywith the wrong string. The space key is' ', not'Space'. Arrow keys are'ArrowUp', not'Up'. - Putting a key handler on a non-focusable element. Without
tabIndex, it never fires. - Using
onMouseOverfor hover state. It bubbles from children and flickers. UseonMouseEnter. - Forgetting that a mouse click focuses a button before
onClick. Sequence ismousedown,focus,mouseup,click. A blur handler on another element runs first, which can remove the element you were about to click. - Handling only the mouse. If an action works by click, it must also work by keyboard. Native buttons and links do this for you.
The last item before the common mistakes has an important consequence. If a blur handler hides a menu item, the click on that item may never register, because the item is gone before mouseup. Hiding on blur is safe in the dropdown example above because the relatedTarget check keeps the menu open while focus is inside it.
Summary of choices
| You want to | Use |
|---|---|
| Respond to a click | `onClick` on a `<button>` |
| Hover state that changes behavior | `onMouseEnter` and `onMouseLeave` |
| React to a shortcut or Enter | `onKeyDown` with `e.key` |
| Validate when the user leaves a field | `onBlur` |
| Detect focus leaving a group | `onBlur` plus `e.relatedTarget` and `contains` |
Exercise
A search box should clear itself when the user presses Escape, but it should not submit when Enter is pressed during IME composition. Which event do you attach, which properties do you check, and why is onKeyPress the wrong choice?
Show answer
Attach onKeyDown to the input. Check e.key === 'Escape' to clear the state, and for Enter check !e.nativeEvent.isComposing before submitting. onKeyPress is deprecated in browsers, and it does not fire for non-character keys such as Escape.
Exercise
A dropdown wrapper uses onBlur to close itself, but it closes when the user tabs from the menu button to an item inside it. What is the cause and the fix?
Show answer
React's onBlur bubbles, so it fires on the wrapper whenever focus leaves any child, including when focus moves to another child. In the handler, check e.currentTarget.contains(e.relatedTarget) and close only if it is false.