Handling Events
Event handlers, passing arguments, and how React's events differ from the DOM.
What you'll learn
- Attaching a handler, and the difference between passing and calling
- Passing arguments to a handler
- The event object,
preventDefault, and bubbling - Where handlers belong as components grow
Attaching a handler
Event props are camelCased — onClick, onChange, onSubmit — and they take a
function, not a string:
Both forms are ordinary. Use a named function when the logic is more than a line; use an inline arrow when it is short or needs an argument.
Pass the function, do not call it
This is the most common beginner bug in React:
<button onClick={handleClick}> // right: React calls it on click
<button onClick={handleClick()}> // wrong: called during render
The second one runs handleClick while rendering and passes its return value
— usually undefined — as the handler. If that function sets state, you get an
infinite loop of renders.
The console logs before you touch anything — that is the broken button firing during render. Clicking it does nothing, and React warns that it received a string where it expected a function.
It logs twice, which is worth knowing now: in development React renders each component twice on purpose, so that side effects like this one are obvious rather than silent. In production it renders once.
Passing arguments
Because the handler must be a function, wrap the call in an arrow when you need to pass something:
() => addToCart(name) creates a function that, when called, calls
addToCart(name). That is the whole pattern.
The event object
React passes an event object to your handler. It is a synthetic event — a wrapper with the same interface as the DOM event, normalised across browsers:
event.target.value is how you read what the user typed. That input is a
controlled component — its value comes from state — which is the subject of
Forms and Controlled Inputs.
preventDefault
Returning false does nothing in React. To stop the browser's default
behaviour, call preventDefault — most often to stop a form reloading the page:
Note the handler is on the <form>, not the button. That way it also fires when
the user presses Enter in the field.
Events bubble
An event travels up through ancestors, so a click on the button below also
reaches the surrounding div. stopPropagation ends that journey:
Bubbling is why you can put one handler on a list instead of one per row.
Common mistakes
onClick={handler()}. Calls it during render. Drop the parentheses.onclick. React uses camelCase:onClick.return false. Useevent.preventDefault().- A handler on the submit button. Put
onSubmiton the form so Enter works.
Exercise
Three bugs: the handler is called during render, the argument is passed wrongly, and the form reloads the page on submit. Fix all three — the console should log only when you click.