Sub topic 2
Reading the event object
This chapter assumes you know JavaScript functions and arrow functions, basic JSX, components and props, and the basics of useState. You should also know how to attach a handler such as onClick, which the previous chapter covers.
What React passes to your handler
React calls every handler with one argument, the event object. Its type is SyntheticEvent. It is a wrapper around the browser's native event that behaves the same in every browser. You name the parameter yourself, and most code uses e or event.
function Demo() {
function handleClick(e) {
console.log(e.type);
console.log(e.target);
console.log(e.currentTarget);
}
return (
<button onClick={handleClick}>
<span>Click the label</span>
</button>
);
}If you click the text, the console shows click, then the <span>, then the <button>. The next section explains why those two elements differ.
The properties you will use most
| Property | What it gives you |
|---|---|
| `e.type` | The event name, such as `"click"` or `"change"` |
| `e.target` | The element where the event started |
| `e.currentTarget` | The element your handler is attached to |
| `e.key` | The key pressed, such as `"Enter"` or `"Escape"` (keyboard events) |
| `e.clientX`, `e.clientY` | Pointer position in the viewport (mouse events) |
| `e.nativeEvent` | The underlying browser event |
Other properties depend on the event type. Keyboard events also have e.shiftKey and e.ctrlKey. Mouse events have e.button.
target versus currentTarget
e.target is the deepest element the user interacted with. e.currentTarget is the element whose prop holds the handler. In the example above, the click lands on the <span>, so target is the span. The handler lives on the <button>, so currentTarget is the button.
This matters when you read values. Use currentTarget when you need the element you attached the handler to. Use target only when you want to know exactly what was hit.
function SearchBox() {
function handleKeyDown(e) {
if (e.key === 'Enter') {
console.log('Search for:', e.currentTarget.value);
}
}
return <input onKeyDown={handleKeyDown} />;
}Here the input has no children, so target and currentTarget are the same element. currentTarget still states your intent more clearly.
Reading values in an event handler
Read what you need from the event inside the handler, and save it in a variable if you need it later. Since React 17, React no longer reuses event objects, so older advice about "event pooling" no longer applies. Reading the event after an await is safe. Still, copying the value you need keeps the code easy to follow.
import { useState } from 'react';
function Echo() {
const [text, setText] = useState('');
async function handleChange(e) {
const value = e.target.value;
await Promise.resolve();
setText(value);
}
return (
<>
<input onChange={handleChange} />
<p>{text}</p>
</>
);
}One caveat applies. e.currentTarget is set only while React runs your handler. After an await, it is null. Copy what you need from it before you wait.
Common errors
- Calling the handler during render.
onClick={handleClick()}runs the function while rendering and passes its return value, usuallyundefined, toonClick. WriteonClick={handleClick}. - Using
targetwhen the element has children. If a button contains an icon,e.targetmay be the icon. Readinge.target.valueore.target.datasetthen returns the wrong thing. Usee.currentTarget. - Comparing
e.keywith the wrong string. Values are case-sensitive and follow the browser'sKeyboardEvent.keynames. The space bar is" ", not"Space". - Reading
e.currentTargetafter anawait. It isnullby then, as noted above. - Reaching for
nativeEventtoo early. Most needs are covered by the properties on the synthetic event. UsenativeEventonly for something React does not expose.
Exercise
A <button onClick={handleClick}> contains <img src="save.png" alt="" />. The user clicks the image. In handleClick, which element is e.target and which is e.currentTarget? Which one should you use to read data-id from the button?
Show answer
e.target is the <img>, because that is where the click started. e.currentTarget is the <button>, because the handler is attached to it. Use e.currentTarget.dataset.id, since the image has no data-id attribute.
Exercise
Write a handleKeyDown function for an input that logs "closed" only when the user presses Escape.
Show answer
function handleKeyDown(e) { if (e.key === 'Escape') { console.log('closed'); } }