Sub topic 2
Reading the event object
This chapter assumes you can write JavaScript functions and arrow functions, read basic JSX, pass props to components, and call useState. It also assumes you already know how to attach a handler such as onClick={handleClick}. Here the focus is what React gives that handler as its first argument.
What the handler receives
React calls every event handler with one argument, the event object. By convention it is named e, event, or evt. It is a SyntheticEvent, a wrapper React creates around the browser's native event. The wrapper exposes the same fields you know from the DOM, such as type, target, and key, and it behaves the same way in every browser.
function EventInspector() {
function handleClick(event) {
console.log(event.type); // "click"
console.log(event.target); // the element that was clicked
console.log(event.currentTarget); // the element the handler is attached to
console.log(event.nativeEvent); // the underlying browser MouseEvent
}
return <button onClick={handleClick}>Inspect</button>;
}If a handler declares no parameter, it simply ignores the event. React passes it either way.
Fields you will use most
The synthetic event has the common fields of the DOM Event, plus extra fields that depend on the kind of event.
| Field | Available on | What it tells you |
|---|---|---|
| `type` | All events | The event name, such as `"click"` or `"keydown"` |
| `target` | All events | The element where the event started |
| `currentTarget` | All events | The element whose handler is running |
| `nativeEvent` | All events | The original browser event |
| `key` | Keyboard events | The key's value, such as `"Enter"` or `"a"` |
| `code` | Keyboard events | The physical key, such as `"KeyA"` |
| `shiftKey`, `ctrlKey`, `altKey`, `metaKey` | Keyboard and mouse events | Whether that modifier was held down |
| `clientX`, `clientY` | Mouse and pointer events | Pointer position relative to the viewport |
| `button` | Mouse events | Which button was pressed (0 is left) |
| `relatedTarget` | Focus and mouse events | The other element involved, such as the one losing focus |
Fields from one family do not exist on another. Reading e.key in an onClick handler gives undefined, not an error, and that is a common source of silent bugs.
`target` versus `currentTarget`
These two fields are the most frequent source of confusion. target is the innermost element that received the event. currentTarget is the element your handler is attached to. They differ whenever the event starts on a child of the element with the handler.
function Card() {
function handleClick(e) {
console.log('target:', e.target.tagName);
console.log('currentTarget:', e.currentTarget.tagName);
}
return (
<div onClick={handleClick}>
<button>Open</button>
</div>
);
}Clicking the button logs target: BUTTON and currentTarget: DIV. Clicking the padding of the div, outside the button, logs DIV for both.
Use currentTarget when you want information about the element you attached the handler to. Use target when you care about what the user actually touched. For inputs, onChange is attached directly to the input, so both fields are the same element and e.target.value is the usual idiom.
A related tip: currentTarget is the reliable place to read data- attributes, because target might be an icon or a <span> inside your button.
function DeleteButton({ id, onDelete }) {
function handleClick(e) {
const itemId = e.currentTarget.dataset.id;
onDelete(itemId);
}
return (
<button data-id={id} onClick={handleClick}>
<span>Delete</span>
</button>
);
}If the user clicks the inner <span>, e.target is the span and has no data-id. e.currentTarget is still the button. In this particular case you could also use id from props directly, which is simpler. The dataset approach matters when one shared handler serves many elements.
Reading input values
Form elements expose their current state on target. Which property you read depends on the input type.
import { useState } from 'react';
function Preferences() {
const [name, setName] = useState('');
const [subscribed, setSubscribed] = useState(false);
const [plan, setPlan] = useState('free');
return (
<form>
<input value={name} onChange={e => setName(e.target.value)} />
<label>
<input
type="checkbox"
checked={subscribed}
onChange={e => setSubscribed(e.target.checked)}
/>
Subscribe
</label>
<select value={plan} onChange={e => setPlan(e.target.value)}>
<option value="free">Free</option>
<option value="pro">Pro</option>
</select>
</form>
);
}Text inputs, textareas, and selects use value. Checkboxes and radio buttons use checked. File inputs use files. How the state and the input stay in sync is the subject of a later chapter on controlled inputs. For now, the point is that the event object is where the new value arrives.
Reading keys and modifiers
For keyboard shortcuts, read e.key and the modifier flags. key gives the character or the key's name, which is usually what you want. code identifies the physical key position and is better for games or layout-independent shortcuts.
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('');
} else if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
console.log('Command palette shortcut pressed');
}
}
return (
<input
value={query}
onChange={e => setQuery(e.target.value)}
onKeyDown={handleKeyDown}
/>
);
}The check e.ctrlKey || e.metaKey covers both Windows and Linux (Ctrl) and macOS (Command). Key names are case sensitive: with Shift held, e.key for the letter K is "K", not "k".
The event is only valid during the handler
Before React 17, React reused synthetic event objects and cleared their fields after the handler returned. This was called event pooling, and it broke any code that read the event after an await or inside a setTimeout. Modern React no longer pools events, so the object itself stays intact. Two things still catch people out, though.
e.currentTargetis set back tonullonce the handler has finished running. Reading it after anawaitgivesnull.e.targetstill points to the same DOM element, but that element is mutable. If you reade.target.valueafter anawait, you get the input's value at that later moment, which may differ from what it was when the event fired.
The safe habit is to copy what you need into local variables at the top of the handler.
function LiveSearch() {
async function handleChange(e) {
const value = e.target.value;
const form = e.currentTarget.form;
const response = await fetch(`/api/search?q=${encodeURIComponent(value)}`);
const results = await response.json();
console.log(results, form); // value and form are safe to use here
}
return <input type="search" onChange={handleChange} />;
}Also be careful about passing the event itself into state, for example setLastEvent(e). The object holds references to DOM nodes, and currentTarget will already be null when you read it later. Store the specific values you need instead.
Using `nativeEvent`
Sometimes React's wrapper does not expose a field that the browser's event has. In that case, e.nativeEvent gives you the original object. For example, a wheel event's deltaMode, or details of an InputEvent such as inputType, are reachable this way.
function Editor() {
function handleInput(e) {
console.log(e.nativeEvent.inputType); // for example "insertText"
}
return <textarea onInput={handleInput} />;
}Treat nativeEvent as an escape hatch. Code that depends on it is tied to browser behavior that React normally hides from you. Calling methods like stopPropagation on the native event also does not behave the same as calling them on the synthetic one, a point covered in the chapter on stopping propagation.
Common errors
- Calling the handler instead of passing it. Writing
onClick={handleClick()}runs the function during render and passes its return value to React. WriteonClick={handleClick}. - Reading the wrong field for the event type.
e.keyon a click ande.clientXon a keydown are bothundefined. Check the table above against the event you attached. - Using
targetwherecurrentTargetis needed. If clicking a child element makes yourdatasetoridlookup returnundefined, this is the cause. - Reading
currentTargetafter anawait. It isnullby then. Copy it into a variable first. - Comparing
e.keyto the wrong string. Use"Enter","Escape"," "(a single space) for the space bar, and"ArrowUp". Logginge.keyis the fastest way to confirm a name. - Assuming
target.valueexists. On a<div>or<button>click,targetmay not have avaluethat means what you expect. Only form controls carry user-entered values.
Exercise
A <div onClick={handleClick}> contains a <button> with a child <span>Save</span>. The user clicks the text "Save". In handleClick, what are e.target and e.currentTarget, and why would e.target.dataset.id be unreliable if the data-id attribute is on the button?
Show answer
e.target is the <span>, because it is the innermost element that received the click. e.currentTarget is the <div>, because that is where the handler is attached. The data-id attribute is on the button, so e.target.dataset.id is undefined when the span was clicked. Put the handler on the button and read e.currentTarget.dataset.id, which always refers to the element the handler is attached to.
Exercise
This handler logs null for the form. Fix it so it logs the form element.
async function handleChange(e) {
await fetch('/api/ping');
console.log(e.currentTarget.form);
}
Show answer
React resets e.currentTarget to null after the handler's synchronous part finishes, and the await pauses the handler. Read it first and use the saved variable:
async function handleChange(e) {
const form = e.currentTarget.form;
await fetch('/api/ping');
console.log(form);
}