Event Handling in React

By Syncfusion®, Inc. · Last updated

Events and event handlers, synthetic events and the event object, click, mouse and keyboard events, passing values to handlers, typing handlers, preventDefault and event propagation.

Introduction to Events

An event is something that happens on the page, such as a click, a key press or a mouse move. Event handling means running your own code when an event happens.

In React, you add an event to an element with a prop like onClick. You give it a function. React calls that function when the event happens. This function is called an event handler.

Animation: the user clicks a button, React calls the onClick handler, and the handler updates the page

Add to cart<button>1. user clicksonClickevent handlerhandleClick()2. React calls itCart (1)page updates3. state changes

An event happens, React calls your handler, and the handler updates the page.

Real-World Example

In a bookshop app, each book card has an Add to cart button with onClick={() => addToCart(book.id)}. A search box has onChange and reads e.target.value on every key press.

React calls these functions only when the user clicks or types. Each function updates state, and the page shows the new cart count and the new search results.

<button onClick={handleClick}>Add to cart</button>

Here, onClick is the event, and handleClick is the event handler.

Event names in React use camelCase: onClick, onChange, onKeyDown. You pass a function, not a string.

Synthetic Events and Event Object

When an event happens, React calls your handler and gives it one input. This input is called the event object. It holds information about what happened.

Most people name it e or event:

function handleClick(e) {
  console.log(e.type); // "click"
}

React's event object is called a synthetic event. It is React's own version of the browser's event. It works the same way in every browser, so you do not have to worry about browser differences.

Animation: each browser sends its own native event; React wraps it in one synthetic event object with the same fields everywhere

Chrome clickFirefox clickSafari clickReact wraps ite (synthetic event)e.type → "click"e.target → the <button>e.preventDefault()

React gives your handler the same event object in every browser.

Useful parts of the event object:

  • e.type — the kind of event, such as "click" or "keydown".
  • e.target — the element where the event started.
  • e.currentTarget — the element that has the handler.
  • e.preventDefault() — stops the browser's normal action.
  • e.stopPropagation() — stops the event from going up to parent elements.

Click the button and look at the console. The event object tells you the event type, which button was clicked, and where the mouse was.

e: any means "any type". Later in this lesson, you will learn the correct type to use.

Click Events

onClick runs a function when an element is clicked. You can write the handler in two ways.

  • Way 1: onClick={handleLike} gives React the function handleLike. Use this when the handler has more than one line.
  • Way 2: onClick={() => setLikes(0)} writes a short function right there. Use this for one short line.

Do not write onClick={handleLike()}. The () runs the function at once, while the page is drawn, not when you click.

Mouse Events

Mouse events run when the mouse moves over an element or clicks it. These are the most common ones:

EventWhen it runs
onClickThe element is clicked
onDoubleClickThe element is clicked twice quickly
onMouseEnterThe mouse moves onto the element
onMouseLeaveThe mouse moves off the element
onMouseMoveThe mouse moves while over the element

Move the mouse onto the box, move it around, double-click it, then move it away. Each action runs a different handler.

Keyboard Events

Keyboard events run when a key is pressed in an element that has focus, such as an input box.

  • onKeyDown runs when a key is pressed down.
  • onKeyUp runs when the key is let go.

The event object has e.key. It holds the name of the key, such as "a", "Enter" or "Escape".

Click in the box and type. Look at this line in handleKeyDown:

if (e.key === "Enter" && text !== "") {

It means: if the key is Enter, and the box is not empty, add the book. Press Escape to clear the box.

Passing Parameters to Event Handlers

Sometimes the handler needs extra information, such as which book was clicked. Wrap the call in an arrow function, and pass the value inside it.

<button onClick={() => addToCart("Atomic Habits")}>Add</button>

The arrow function runs only on click. Then it calls addToCart with the book name.

Both buttons use the same addToCart function. Each button sends its own book name.

You can also pass the event object along with your own value:

<button onClick={(e) => addToCart("Atomic Habits", e)}>Add</button>

Typing Event Handlers

In TypeScript, you can give the event object a proper type instead of any. Then TypeScript knows what is inside it, and your editor can suggest its parts.

React gives a type for each kind of event. You import them from "react":

TypeUse it forExample element
MouseEvent<HTMLButtonElement>Clicks and mouse events<button>
ChangeEvent<HTMLInputElement>Typing in a box<input>
KeyboardEvent<HTMLInputElement>Key presses<input>
FormEvent<HTMLFormElement>Submitting a form<form>

The part in < > is the kind of element. For example, HTMLButtonElement means a <button>.

Look at this line:

function handleChange(e: ChangeEvent<HTMLInputElement>) {

It says: e is a change event that comes from an <input>. Because of this type, TypeScript knows that e.target.value is text.

If you write the handler inline, such as onChange={(e) => setName(e.target.value)}, you do not need a type. TypeScript works it out for you.

Preventing Default Behavior

Some elements have a default behavior: something the browser does by itself.

  • Submitting a <form> reloads the page.
  • Clicking a link <a> opens another page.

To stop this, call e.preventDefault() in your handler. Then only your code runs.

Type an email and press Subscribe. The page does not reload. Instead, the thank-you message appears.

Without e.preventDefault(), a normal web page would reload, and the message would be lost.

Event Propagation

When you click an element, the click event does not stop there. It also goes up to the element's parent, then that parent's parent, and so on. This is called event propagation, or bubbling.

Animation: a click on the button runs its handler, then bubbles up to the card and then to the page Page (onClick)Book card (onClick)Button (onClick)

1. Button clicked2. Card clicked3. Page clickede.stopPropagation() stops the event going up

The click starts at the button, then goes up to each parent with an onClick.

So if the button and its parent card both have onClick, one click runs both handlers. Usually you do not want this.

To stop the event from going up, call e.stopPropagation() in the button's handler.

Press Add (no stop). The log shows two lines: the button ran, and then the card ran too. Press Add (with stop). The log shows only one line, because e.stopPropagation() stopped the click from reaching the card.

e.preventDefault() stops the browser's own action. e.stopPropagation() stops the event from going up to the parents. They do different jobs.

Common mistakes

MistakeWhat you seeFix
Calling the handler: onClick={handleClick()}It runs when the page loads, not on clickPass the function: onClick={handleClick}
Passing a value without an arrow: onClick={add("Atomic Habits")}It runs at once, and may loop foreverWrap it: onClick={() => add("Atomic Habits")}
Lower-case event name: onclickNothing happens on clickUse camelCase: onClick
Passing a string: onClick="handleClick()"TypeScript errorPass a function in braces
Forgetting e.preventDefault() in a formThe page reloads and your state is lostCall e.preventDefault() first in onSubmit
A button inside a clickable cardOne click runs both handlersCall e.stopPropagation() in the button's handler
onKeyDown on a <div> that cannot get focusKey presses do nothingPut it on an <input>, or add tabIndex={0}

Check Yourself

Exercises

What to Remember

  • An event handler is a function you pass to a prop like onClick. Pass the function, do not call it.
  • Use an arrow function to pass a value: onClick={() => add("Atomic Habits")}.
  • e.preventDefault() stops the browser's own action. e.stopPropagation() stops the event from going up.

Next: Conditional Rendering