Event Handling in React is the process of managing user interactions within the application (e.g., button clicks, form submissions, keyboard input). React implements a Synthetic Event System that wraps the browser’s native event system, ensuring events behave consistently across all browsers.
1. Key Differences from Native HTML
Handling events in React is similar to standard HTML/JavaScript, but with three important syntax differences:
- CamelCase: React event handlers are named using camelCase (e.g.,
onClick,onChange), not lowercase (onclick). - Function Reference: You pass the event handler as a function reference (or a function itself), not a string of code.
- Prevent Default: In native JavaScript, you might return
falseto prevent the default behavior (like form submission). In React, you must explicitly call the event object’s method:event.preventDefault().
2. The Synthetic Event Object
When an event is triggered, React passes a Synthetic Event Object to your handler function. This object is fully W3C compliant and provides access to standard methods and properties, such as:
event.target: The DOM element that triggered the event.event.preventDefault(): Stops the browser’s default action.
3. Execution Example: Click Handler
The most common event is the click event, handled by the onClick attribute.
Execution Example: Click Counter
In your my-first-app/src directory:
- Open the main file,
App.js. - Replace its content with the following code:
import React from 'react';
function App() {
// 1. Define the event handler function
function handleClick() {
console.log("Button was clicked!");
alert("The button was clicked!");
}
// 2. Define a handler that accepts the synthetic event object
function handleAnchorClick(event) {
// Stop the link from navigating to Google
event.preventDefault();
console.log("Navigation prevented.");
}
return (
<div className="EventDemo">
<h1>Event Handling Demo</h1>
{/* Attach the function reference to the onClick attribute.
Note: No parentheses are used here to avoid immediate execution. */}
<button onClick={handleClick}>
Log and Alert Click
</button>
<br /><br />
{/* Anchor tag handler */}
<a href="https://www.google.com" onClick={handleAnchorClick}>
Click to See PreventDefault
</a>
</div>
);
}
export default App;
- Local Execution: Run
npm startin your project’s terminal. - Observation: Clicking the button executes the
handleClickfunction. Clicking the anchor link triggershandleAnchorClick, which successfully prevents the page from navigating.
4. Passing Arguments to Event Handlers
Often, you need to pass extra parameters (like an item ID) to an event handler, in addition to the default event object. Since attaching a function with parentheses (handleClick(id)) executes it immediately upon rendering, you must wrap the function call in an Arrow Function or an anonymous function.
Execution Example: Passing an Item ID
Modify the App.js component to include the following:
import React from 'react';
function App() {
// Handler that accepts an ID argument
function handleDelete(itemId, event) {
// You can still access the event object if needed
console.log(`Deleting item with ID: ${itemId}`);
console.log("Event type:", event.type);
}
return (
<div className="EventDemo">
<h1>Passing Arguments</h1>
{/* 1. Use an Arrow Function to wrap the handler call.
The arrow function executes only on the click event, and it calls
handleDelete with the specified ID (10) and the event object.
*/}
<button onClick={(event) => handleDelete(10, event)}>
Delete Item 10
</button>
{/* 2. Alternative: If the event object is not needed, you can omit it. */}
<button onClick={() => handleDelete(20)}>
Delete Item 20 (No Event Object)
</button>
</div>
);
}
export default App;
This pattern ensures the handler is only executed when the event occurs, while still allowing you to pass necessary custom data.
