Handling events in React is similar to handling events on DOM elements, with two key differences: React events are named using camelCase (onClick, onChange), and you pass a function handler directly rather than a string.
React wraps native browser DOM events in a cross-browser SyntheticEvent instance. This guarantees consistent behavior across Chrome, Safari, Firefox, and Edge while maintaining high performance through event delegation.
flowchart LR
A["Browser Event (Click)"] --> B["Document Root Event Listener"]
B --> C["React SyntheticEvent Engine"]
C --> D["Target Component Event Handler"]
import React, { useState } from 'react';
export default function InteractivePanel() {
const [inputText, setInputText] = useState('');
const [clickCount, setClickCount] = useState(0);
// 1. Passing Event Parameter
const handleInputChange = (event) => {
setInputText(event.target.value);
};
// 2. Prevent Default Form Submission Behavior
const handleSubmit = (event) => {
event.preventDefault();
alert(`Form submitted with payload: ${inputText}`);
};
// 3. Passing Custom Parameters to Event Handlers
const handleItemDelete = (id, e) => {
e.stopPropagation(); // Stop event bubbling
alert(`Deleting item #${id}`);
};
return (
<form onSubmit={handleSubmit} className="panel">
<div>
<label htmlFor="user-input">Search Term:</label>
<input
id="user-input"
type="text"
value={inputText}
onChange={handleInputChange}
/>
</div>
<button type="submit">Submit Form</button>
<div style={{ marginTop: '1rem' }}>
<button type="button" onClick={() => setClickCount((prev) => prev + 1)}>
Clicked {clickCount} times
</button>
<button type="button" onClick={(e) => handleItemDelete(42, e)}>
Delete Item #42
</button>
</div>
</form>
);
}
onClick={handleClick}, not onClick={handleClick()}. Calling the function directly executes it immediately during rendering rather than when clicked.event.preventDefault(): In React, returning false inside an event handler does NOT prevent default form action behavior. Explicitly call e.preventDefault().Create a button that logs the cursor's clientX and clientY coordinates whenever the user clicks it.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With