Sub topic 1
Handling events on form elements
React handles events on form elements through props like onChange and onSubmit. This chapter explains how those handlers work. Later chapters build controlled inputs on top of them.
Prerequisites
This chapter assumes you know:
- JavaScript objects, arrow functions, and destructuring.
- How to write a basic React function component with JSX.
- Passing props to components.
- The common HTML form elements:
input,select,textarea,button, andform.
You do not need to know useState yet. The examples here only log to the console, and the next chapter introduces state.
How React attaches event handlers
In plain HTML you can write onclick="doThing()" with a string. In JSX you pass a function, and the prop name is camelCase.
export default function ClickDemo() {
function handleClick() {
console.log('Clicked');
}
return <button onClick={handleClick}>Click me</button>;
}Pass the function itself, not the result of calling it. Writing onClick={handleClick()} runs the function during rendering and passes its return value, usually undefined, to the prop.
React does not attach a listener to every element. It listens for events once, at the root of your app, and dispatches them to the handlers you declared. This is called event delegation. You rarely need to think about it, but it explains why the event object you receive is not exactly the browser's native one.
The synthetic event object
Every handler receives a SyntheticEvent. This is a wrapper around the browser's native event. It has the same fields you know from the DOM, such as target, currentTarget, type, preventDefault(), and stopPropagation(). React normalizes the wrapper so it behaves the same across browsers.
| Property or method | Meaning |
|---|---|
| `e.target` | The element that triggered the event. |
| `e.currentTarget` | The element the handler is attached to. |
| `e.type` | The event name, such as `change` or `submit`. |
| `e.preventDefault()` | Stops the browser's default action. |
| `e.stopPropagation()` | Stops the event from reaching parent handlers. |
| `e.nativeEvent` | The underlying browser event. |
In older React versions (16 and earlier), the synthetic event was pooled and its fields were cleared after the handler returned. Since React 17 this no longer happens, so reading e.target inside an async callback works. Old tutorials that call e.persist() are describing the earlier behavior.
The events you use on forms
Forms mostly rely on a small set of events.
| Event prop | Fires when | Typical use |
|---|---|---|
| `onChange` | The value of an input changes | Reading what the user typed or selected |
| `onSubmit` | The form is submitted | Validating and sending data |
| `onFocus` | An element gains focus | Showing hints |
| `onBlur` | An element loses focus | Marking a field as touched |
| `onClick` | An element is clicked | Buttons, checkboxes |
| `onKeyDown` | A key is pressed | Custom keyboard shortcuts |
| `onReset` | The form is reset | Clearing custom state |
onChange fires on every edit
This is the most important difference from plain HTML. In the DOM, the change event on a text input fires only when the input loses focus after a modification. React's onChange behaves like the DOM input event instead. It fires on every keystroke, paste, cut, and drag-and-drop edit.
export default function LiveLogger() {
function handleChange(e) {
console.log('Current text:', e.target.value);
}
return (
<label>
Type here
<input onChange={handleChange} />
</label>
);
}Type "hi" and the console shows h, then hi. This per-keystroke behavior is what makes controlled inputs possible.
Reading values from e.target
For form fields, e.target is the DOM element. Which property holds the user's input depends on the element type.
| Element | Property to read |
|---|---|
| Text input, `textarea`, `select` | `e.target.value` |
| Checkbox | `e.target.checked` |
| Radio button | `e.target.value` on the selected radio, or `e.target.checked` |
| File input | `e.target.files` |
The name attribute is also available as e.target.name. A later chapter uses it to share one handler across many fields.
export default function FieldInspector() {
function handleChange(e) {
const { name, type, value, checked } = e.target;
console.log({ name, type, value, checked });
}
return (
<form>
<input name="email" type="email" onChange={handleChange} />
<input name="agree" type="checkbox" onChange={handleChange} />
</form>
);
}Typing in the email field logs checked: false because every input element has a checked property. It only matters for checkboxes and radios.
target versus currentTarget
When an event bubbles, e.target is the element where it started. e.currentTarget is the element whose handler is running. These differ when you attach a handler to a parent.
export default function BubbleDemo() {
function handleChange(e) {
console.log('target:', e.target.name);
console.log('currentTarget:', e.currentTarget.tagName);
}
return (
<form onChange={handleChange}>
<input name="first" />
<input name="second" />
</form>
);
}React's onChange bubbles, so one handler on the form receives changes from every field inside it. Typing in the first input logs target: first and currentTarget: FORM. This is a useful way to handle many fields, but it also means a handler on a parent will see events from fields you did not expect, such as ones in nested components.
In a submit handler, prefer e.currentTarget to get the form. e.target can be a different element than the form in some cases, while currentTarget is always the element the handler is attached to.
Preventing default behavior
Some events trigger browser behavior you may want to replace. The most common case is form submission. By default, submitting a form makes the browser send a request and reload the page. In a React app you usually want to handle the data yourself.
export default function SubmitDemo() {
function handleSubmit(e) {
e.preventDefault();
console.log('Handled in JavaScript, no page reload');
}
return (
<form onSubmit={handleSubmit}>
<input name="q" />
<button type="submit">Go</button>
</form>
);
}Without e.preventDefault(), the page reloads and your console output disappears. A later chapter covers submission in full.
Two details are worth knowing now:
- Attach the handler to
onSubmiton theform, notonClickon the button. Pressing Enter in a text field submits the form without clicking the button, andonClickwould miss it. - A
buttoninside aformdefaults totype="submit". If a button should not submit, such as a "Show password" toggle, writetype="button".
Passing arguments to handlers
Sometimes a handler needs extra information, such as which row of a list it belongs to. Wrap the call in an arrow function.
const colors = ['red', 'green', 'blue'];
export default function ColorPicker() {
function choose(color) {
console.log('Chose', color);
}
return (
<div>
{colors.map((color) => (
<button key={color} type="button" onClick={() => choose(color)}>
{color}
</button>
))}
</div>
);
}The arrow function is created during render, but choose(color) runs only when the click happens. If you need the event too, accept it in the arrow function and forward it: onClick={(e) => choose(color, e)}.
Common errors
- Calling the function in JSX.
onChange={handleChange()}runs on every render. WriteonChange={handleChange}. - Using
class-style names. The props areonChange, notonchange. Lowercase names are ignored with a warning. - Forgetting
preventDefaulton submit. The page reloads and you lose in-memory data. - Reading
e.target.valueon a checkbox. A checkbox'svalueis a fixed string, usually"on". Readchecked. - Expecting
onChangeto fire on blur. It fires on each edit. UseonBlurfor blur behavior. - Putting a value on an input without
onChange. React warns that the field is read-only. The next chapters explain this pattern.
Summary
Handlers are functions passed to camelCase props. They receive a synthetic event that wraps the native one. onChange fires on every edit. Use e.target.value or e.target.checked to read input, e.currentTarget to refer to the element with the handler, and e.preventDefault() to stop the browser's default action on submit.
Exercise
A form has a checkbox with name="agree" and an onChange handler that logs e.target.value. It always logs "on", whether the box is ticked or not. What is wrong, and how do you fix it?
Show answer
A checkbox's value attribute is a fixed string that defaults to "on". The state of the box lives in checked. Change the handler to log e.target.checked, which is true when ticked and false otherwise.
Exercise
A form contains a button labeled "Show password" that is meant to toggle the field's visibility. Clicking it reloads the page. Why does this happen, and what is the smallest fix?
Show answer
A button inside a form defaults to type="submit", so clicking it submits the form and the browser reloads the page. Add type="button" to the toggle button so it no longer submits.
Exercise
You attach onChange={handleChange} to a form element containing two inputs. In handleChange, which of e.target and e.currentTarget tells you which input changed, and what does the other one refer to?
Show answer
e.target is the input that changed, so e.target.name identifies it. e.currentTarget is the form, because that is the element the handler is attached to.