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 eventevent.currentTarget- The element the handler is attached toevent.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
Useevent.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
Useevent.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
// Good - separate concerns
const handleValidation = (data) => { /* validate */ };
const handleSubmit = (event) => {
event.preventDefault();
const data = new FormData(event.target);
if (handleValidation(data)) {
// submit
}
};
// Avoid - doing too much in one handler