Sub topic 1
Handling events on form elements
Prerequisites
This chapter assumes you know the following:
- JavaScript objects, arrow functions and destructuring.
- How to write a React function component with JSX.
- Basic HTML form elements such as
input,selectandbutton.
You don't need useState yet. The next chapter covers it.
How React handles events
React lets you attach event handlers as props on JSX elements. The prop names are camelCase, so onclick becomes onClick and onsubmit becomes onSubmit. You pass a function, not a string.
React calls your handler with a synthetic event. This is a wrapper around the browser's native event that behaves the same way in every browser. It gives you the familiar properties, such as target, currentTarget, preventDefault() and stopPropagation().
export default function ClickDemo() {
function handleClick(e) {
console.log('Clicked', e.currentTarget.tagName);
}
return <button onClick={handleClick}>Click me</button>;
}Pass handleClick, not handleClick(). Writing onClick={handleClick()} calls the function during rendering and passes its return value to React.
The events you use most on forms
| Event prop | Fires when | Typical use |
|---|---|---|
| `onChange` | The value of an input changes | Reading what the user typed |
| `onSubmit` | The form is submitted | Validating and sending data |
| `onBlur` | A field loses focus | Marking a field as touched |
| `onFocus` | A field gains focus | Showing hints |
React's onChange differs from the native DOM change event. The native event fires when the user leaves a text field. React's onChange fires on every keystroke, as the native input event does. This is what makes live updates possible.
Reading the value from the event
Inside an onChange handler, e.target is the element that changed. Its value property holds the current text.
export default function EchoInput() {
function handleChange(e) {
console.log('Typed:', e.target.value);
}
return (
<label>
Type here
<input onChange={handleChange} />
</label>
);
}For checkboxes, read e.target.checked instead. A later chapter covers this.
e.target and e.currentTarget are not the same thing:
e.targetis the element that triggered the event.e.currentTargetis the element the handler is attached to.
On an onSubmit handler, e.currentTarget is the form. e.target could in principle be a nested element. Use currentTarget when you want the form itself.
Stopping the default submit
A browser form submits by default. It sends a request and reloads the page. In a React app you usually want to handle the data in JavaScript, so you call e.preventDefault() first.
export default function PingForm() {
function handleSubmit(e) {
e.preventDefault();
const data = new FormData(e.currentTarget);
console.log('Name:', data.get('name'));
}
return (
<form onSubmit={handleSubmit}>
<input name="name" defaultValue="Ada" />
<button type="submit">Send</button>
</form>
);
}Attach onSubmit to the form, not to the button's onClick. Pressing Enter inside a field also submits the form, and only onSubmit catches that.
Common errors
- Calling the handler while rendering.
onChange={handleChange()}runs the function immediately. UseonChange={handleChange}, oronChange={(e) => handleChange(e, 'email')}to pass extra arguments. - Forgetting
preventDefault(). The page reloads and any state is lost. - Using
onClickon a submit button. Enter-key submissions are missed. - Using
e.targetinonSubmit. Prefere.currentTargetto get the form.
Exercise
A form has <form onSubmit={handleSubmit}> and a submit button. When the user clicks the button, the page reloads and the console message from handleSubmit appears only briefly. What is missing, and where should it go?
Show answer
The handler is missing e.preventDefault(). Call it at the top of handleSubmit, before any other logic, so the browser doesn't perform its default submission and reload the page.
Exercise
What is the difference between onChange={save} and onChange={save()}?
Show answer
onChange={save} passes the function to React, which calls it with the event when the value changes. onChange={save()} calls save during rendering and passes its return value, usually undefined, as the handler.