Event Handling in React – How to Manage User Actions in JSX
Event handling in React involves configuring your JSX elements to respond to user interactions on them (such as mouse clicks, form submission, and element focus).
This post provides a snapshot of the comprehensive Code React Sweetly book. It serves as a quick reference guide.
Syntax
Section titled “Syntax”<jsxTag onEvent={handleEvent}>UI Content</jsxTag>jsxTag: React elements like<div>,<button>, and<input>.onEvent: The event listener you want to add to the React element. Some examples areonClick,onBlur, andonHover.handleEvent: The event handler function you want to use to handle (respond to) the specifiedonEventtype.
Types of Event Handlers
Section titled “Types of Event Handlers”There are two typical ways to define the event handler function in React:
- Inline event handler: A function defined directly on a JSX element’s opening tag as the value of the event listener prop (
onEvent). - Referenced event handler: A function defined as a separate (independent) logic and linked to an event listener attribute (
onEvent) by name referencing.
Example: Inline event handler
Section titled “Example: Inline event handler”export default function App() { return ( <h1 onClick={() => alert("You clicked the heading!")}> Oluwatobi is my name. </h1> );}Example: Referenced event handler
Section titled “Example: Referenced event handler”export default function App() { return <h1 onClick={handleClick}>Oluwatobi is my name.</h1>;}
const handleClick = () => alert("You clicked the heading!");Dive Deep
Section titled “Dive Deep”The Complete Event Handling guide is an actionable guide that breaks down React’s event system and shows you how to manage events on JSX elements effectively. Here are the main concepts it covers:
- The different types of event handlers.
- How to pass arguments.
- How to access event objects.
- Understand the primary differences between HTML and React events.
