React Fundamentals: Event Handling
Explanation
Event handling in React allows you to respond to user interactions like clicks, typing, form submissions, and more. React events work similarly to regular DOM events but with some key differences:
Key Concepts:
-
Synthetic Events: React uses a wrapper around native browser events called "Synthetic Events" that work consistently across all browsers.
-
CamelCase Naming: Event handlers in React are named using camelCase (onClick, onChange) rather than lowercase (onclick, onchange).
-
Event Binding: You need to bind event handlers to access the correct
thiscontext in class components, or use arrow functions/hooks in functional components. -
Prevent Default: You must explicitly call
event.preventDefault()to prevent default browser behavior.
Basic Pattern:
<button onClick={handleClick}>Click me</button>
Examples
Example 1: Basic Click Event
function App() {
const handleClick = () => {
console.log('Button clicked!');
};
return <button onClick={handleClick}>Click Me</button>;
}
Example 2: Event with Parameters
function App() {
const handleGreeting = (name) => {
alert(`Hello, ${name}!`);
};
return (
<button onClick={() => handleGreeting('John')}>
Say Hello
</button>
);
}
Example 3: Form Events
function Form() {
const [inputValue, setInputValue] = useState('');
const handleChange = (event) => {
setInputValue(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
console.log('Form submitted:', inputValue);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={handleChange}
/>
<button type="submit">Submit</button>
</form>
);
}
Example 4: Multiple Events
function InteractiveBox() {
const [count, setCount] = useState(0);
const handleMouseEnter = () => {
console.log('Mouse entered');
};
const handleMouseLeave = () => {
console.log('Mouse left');
};
const handleClick = () => {
setCount(count + 1);
};
return (
<div
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
onClick={handleClick}
style={{ padding: '20px', border: '1px solid black' }}
>
Clicked {count} times
</div>
);
}
Interview Questions & Answers
Q1: What are Synthetic Events in React?
Answer: Synthetic Events are React's cross-browser wrapper around native browser events. They normalize events so they work identically across all browsers. They pool events for performance, which means the event object is reused and all properties are nullified after the event callback is invoked. This is why you might need to call event.persist() if you need to access the event asynchronously.
Q2: How do you prevent default behavior in React events?
Answer: You need to explicitly call event.preventDefault() within your event handler:
function Form() {
const handleSubmit = (event) => {
event.preventDefault();
// Handle form submission
};
return <form onSubmit={handleSubmit}>...</form>;
}
Q3: What's the difference between onClick={handleClick()} and onClick={handleClick}?
Answer:
onClick={handleClick}passes the function reference, so it's called only when the event occurs.onClick={handleClick()}immediately invokes the function during rendering and passes its return value (usuallyundefined) as the handler, which doesn't work.
Q4: How do you pass parameters to event handlers?
Answer: You can use an arrow function wrapper or bind the function:
// Using arrow function
<button onClick={() => handleDelete(id)}>Delete</button>
// Using bind
<button onClick={handleDelete.bind(this, id)}>Delete</button>
// For class components, bind in constructor
this.handleDelete = this.handleDelete.bind(this, id);
Q5: Why might you need to bind event handlers in class components?
Answer: In class components, this is not automatically bound to the instance. If you don't bind it, this will be undefined when the function is called. Solutions include:
- Binding in constructor
- Using arrow functions as class properties
- Using arrow functions in render (not recommended for performance)
Q6: How do React events differ from native DOM events?
Answer:
- React events are named using camelCase
- React events are Synthetic Events (cross-browser wrappers)
- In React, you return
falsefrom event handlers doesn't prevent default behavior - React events use event delegation, attaching most handlers at the document root level
Q7: What is event pooling in React and why is it used?
Answer: Event pooling is a performance optimization where React reuses event objects. After an event handler is called, all properties on the event object are nullified. This reduces garbage collection overhead. If you need to access the event asynchronously, you must call event.persist() to remove it from the pool.
Q8: How would you handle multiple form inputs efficiently?
Answer: Use a single handler with dynamic property names:
function Form() {
const [formData, setFormData] = useState({
name: '',
email: '',
password: ''
});
const handleChange = (event) => {
const { name, value } = event.target;
setFormData(prev => ({
...prev,
[name]: value
}));
};
return (
<form>
<input name="name" value={formData.name} onChange={handleChange} />
<input name="email" value={formData.email} onChange={handleChange} />
<input name="password" value={formData.password} onChange={handleChange} />
</form>
);
}
Q9: What's wrong with inline arrow functions in render for event handlers?
Answer: Inline arrow functions create a new function on every render, which can cause:
- Performance issues due to unnecessary re-renders of child components
- Problems with
shouldComponentUpdateorReact.memooptimizations - Memory overhead from frequent garbage collection
Q10: How do you handle keyboard events in React?
Answer: Use keyboard event handlers like onKeyDown, onKeyUp, or onKeyPress:
function InputWithEnter() {
const handleKeyPress = (event) => {
if (event.key === 'Enter') {
console.log('Enter key pressed!');
}
};
return <input onKeyPress={handleKeyPress} />;
}
Your Feedback
Help us improve by sharing your thoughts
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.
