Skip to main content

Adding Interactivity

React lets you add event handlers to your JSX. Event handlers are functions that execute in response to user interactions like clicking, hovering, or typing.

Event Handlers

To add an event handler, define a function and pass it as a prop to the appropriate JSX element:
Common mistake: Don’t call the function when passing it!
  • ✅ Correct: onClick={handleClick}
  • ❌ Wrong: onClick={handleClick()} (calls immediately)

Inline Event Handlers

For simple handlers, you can define them inline:

Common Event Types

React supports all standard DOM events. Here are the most commonly used:

Click Events

Input Events

Mouse Events

Keyboard Events

The Event Object

Event handlers receive an event object as their first argument:

Useful Event Properties

  • event.target - The element that triggered the event
  • event.currentTarget - The element the handler is attached to
  • event.type - The type of event (“click”, “change”, etc.)
  • event.key - The key pressed (for keyboard events)
  • event.clientX / event.clientY - Mouse position

Preventing Default Behavior

Use event.preventDefault() to stop the browser’s default action:
When to use preventDefault:
  • Form submissions (to handle with JavaScript)
  • Link clicks (for client-side routing)
  • Context menu events (to show custom menus)
  • Drag and drop operations

Event Propagation

Events “bubble up” from child to parent elements:

Stopping Propagation

Use event.stopPropagation() to prevent the event from bubbling:

Passing Arguments to Event Handlers

There are two ways to pass additional arguments:

Using Arrow Functions

Using bind

Complete Interactive Example

Here’s a complete example with multiple event types:

Best Practices

Next Steps

Event handlers often need to update the UI. Learn how to manage changing data with state.