Events
Interacting with the user
10-15 min
Event Handling in React
Event handling in React is similar to handling events in the DOM, but with a few important differences. React uses a synthetic event system to optimize performance and ensure consistency across browsers.
Basic Events
Handling clicks
function Button() {
const handleClick = (event) => {
console.log('Button clicked!');
// event is a React synthetic event
};
return <button onClick={handleClick}>Click me</button>;
}
Form events
function LoginForm() {
const handleSubmit = (event) => {
event.preventDefault(); // Prevents the page from reloading
console.log('Form submitted');
};
return (
<form onSubmit={handleSubmit}>
<input type="text" />
<button type="submit">Log in</button>
</form>
);
}
Synthetic Events
React wraps browser events in synthetic events in order to:
- Ensure consistency across browsers
- Optimize performance
- Handle update batching
Usage example
function EventExample() {
const handleMouseEnter = (event) => {
// event is a synthetic event
console.log('Event type:', event.type);
console.log('Target:', event.target);
console.log('Position:', event.clientX, event.clientY);
};
return (
<div onMouseEnter={handleMouseEnter}>
Hover over me
</div>
);
}
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion