Event Handling
Event Handling
React uses a camelCase naming convention for events.
Basic Event Handling
function Button() {
const handleClick = () => {
console.log("Button clicked!");
};
return <button onClick={handleClick}>Click me</button>;
}
Event with Arguments
function TodoItem({ todo, onDelete }) {
return (
<div>
<span>{todo.text}</span>
<button onClick={() => onDelete(todo.id)}>
Delete
</button>
</div>
);
}
Common Events
function Form() {
const handleSubmit = (e) => {
e.preventDefault();
console.log("Form submitted");
};
const handleChange = (e) => {
console.log(e.target.value);
};
const handleKeyDown = (e) => {
if (e.key === "Enter") {
console.log("Enter pressed");
}
};
return (
<form onSubmit={handleSubmit}>
<input onChange={handleChange} onKeyDown={handleKeyDown} />
<button type="submit">Submit</button>
</form>
);
}
Synthetic Events
Synthetic Events
React wraps native DOM events in Synthetic Events for cross-browser compatibility.
What are Synthetic Events?
- Wrapper around native DOM events
- Same interface as native events
- Cross-browser compatible
- Pooled for performance
Accessing Native Event
function handleClick(e) {
// Synthetic event
console.log(e.type);
// Access native event if needed
console.log(e.nativeEvent);
console.log(e.nativeEvent.target);
}
Event Object
function handleEvent(e) {
// Common properties
console.log(e.type); // "click"
console.log(e.target); // Element that triggered
console.log(e.currentTarget); // Element with handler
console.log(e.timeStamp); // Time of event
// Mouse events
console.log(e.clientX); // X position
console.log(e.clientY); // Y position
console.log(e.button); // Mouse button
// Keyboard events
console.log(e.key); // "Enter", "Tab", etc.
console.log(e.code); // "KeyA", "Space", etc.
console.log(e.shiftKey); // Shift held?
console.log(e.ctrlKey); // Ctrl held?
}
Preventing Default Behavior
function Link({ href, children }) {
const handleClick = (e) => {
e.preventDefault(); // Prevent navigation
console.log("Link clicked");
};
return (
<a href={href} onClick={handleClick}>
{children}
</a>
);
}
Stopping Propagation
function Parent() {
const handleParent = () => console.log("Parent clicked");
return (
<div onClick={handleParent}>
<Child />
</div>
);
}
function Child() {
const handleChild = (e) => {
e.stopPropagation(); // Don't bubble to parent
console.log("Child clicked");
};
return <button onClick={handleChild}>Click</button>;
}
Event Handler Patterns
Event Handler Patterns
Inline Handlers
// Simple - OK for small handlers
<button onClick={() => console.log("clicked")}>Click</button>
// With arguments
<button onClick={() => handleClick(id)}>Delete</button>
// Avoid complex logic inline
<button onClick={() => {
// Too much logic here
const result = doSomething();
if (result) {
doSomethingElse();
}
}}>Click</button>
Named Handlers
// Better for complex logic
function TodoItem({ todo, onDelete, onToggle }) {
const handleDelete = () => {
if (window.confirm("Are you sure?")) {
onDelete(todo.id);
}
};
const handleToggle = () => {
onToggle(todo.id);
};
return (
<div>
<input
type="checkbox"
checked={todo.done}
onChange={handleToggle}
/>
<span>{todo.text}</span>
<button onClick={handleDelete}>Delete</button>
</div>
);
}
Handler with Event Object
function SearchInput({ onSearch }) {
const handleChange = (e) => {
const value = e.target.value;
onSearch(value);
};
const handleKeyDown = (e) => {
if (e.key === "Enter") {
onSearch(e.target.value);
}
};
return (
<input
onChange={handleChange}
onKeyDown={handleKeyDown}
placeholder="Search..."
/>
);
}
Passing Data to Handlers
function UserList({ users, onSelect }) {
return (
<ul>
{users.map((user) => (
<li key={user.id}>
<button onClick={() => onSelect(user.id)}>
{user.name}
</button>
</li>
))}
</ul>
);
}
Practice Problems
Create a reusable React component implementing React Events. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for React Events using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize React Events for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. How do you name event handlers in React?
2. What is a synthetic event?
3. How do you prevent default form submission?
4. When should you use named handlers?
Flashcards
Question
What is the React event naming convention?
Click to reveal answer
Answer
camelCase: onClick, onChange, onSubmit
Question
What is a synthetic event?
Click to reveal answer
Answer
A wrapper around native DOM events for cross-browser compatibility
Question
How do you prevent default behavior?
Click to reveal answer
Answer
e.preventDefault()
Question
How do you stop event propagation?
Click to reveal answer
Answer
e.stopPropagation()
Question
What is React Events?
Click to reveal answer
Answer
React Events is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.React uses camelCase for event names
- 2.Synthetic events wrap native DOM events
- 3.Use preventDefault to stop default behavior
- 4.Use stopPropagation to prevent bubbling
- 5.Inline handlers are fine for simple cases
Interview Tips
- •Explain synthetic events vs native events
- •Show how to handle form submission
- •Demonstrate event delegation patterns
Cheat Sheet
Cheat Sheet
Event Handling
<button onClick={handleClick}>Click</button>
<button onClick={() => handleClick(id)}>Click</button>
Common Events
- onClick
- onChange
- onSubmit
- onKeyDown
- onMouseEnter
Synthetic Events
function handle(e) {
console.log(e.type); // Event type
console.log(e.target); // Target element
console.log(e.nativeEvent); // Native event
}
Preventing Defaults
e.preventDefault(); // Prevent default action
e.stopPropagation(); // Stop bubbling