On this page
Events in React
React uses Synthetic Events — a cross-browser wrapper around native events with the same API.
Basic Event Handling
function Button() {
const handleClick = () => {
console.log('Button clicked!');
};
return <button onClick={handleClick}>Click me</button>;
}
Passing Arguments
function ItemList({ items }) {
const handleDelete = (id) => {
console.log('Delete item:', id);
};
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name}
<button onClick={() => handleDelete(item.id)}>Delete</button>
</li>
))}
</ul>
);
}
Event Object
function Input() {
const handleChange = (e) => {
console.log(e.target.value);
console.log(e.target.name);
};
return <input name="email" onChange={handleChange} />;
}
Form Submit
function LoginForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (e) => {
e.preventDefault(); // Prevent page reload
console.log({ email, password });
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
<input
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
/>
<button type="submit">Login</button>
</form>
);
}
Common Events
| Event | Element | Use |
|---|---|---|
onClick |
button, div | Clicks |
onChange |
input, select | Value changes |
onSubmit |
form | Form submission |
onKeyDown |
input | Keyboard |
onFocus / onBlur |
input | Focus changes |
onMouseEnter |
div | Hover |
Keyboard Events
function SearchInput() {
const handleKeyDown = (e) => {
if (e.key === 'Enter') {
console.log('Search submitted');
}
if (e.key === 'Escape') {
console.log('Clear search');
}
};
return <input onKeyDown={handleKeyDown} placeholder="Press Enter..." />;
}
stopPropagation and preventDefault
function Card({ onCardClick }) {
const handleButtonClick = (e) => {
e.stopPropagation(); // Don't trigger card click
console.log('Button only');
};
return (
<div onClick={onCardClick} className="card">
<p>Card content</p>
<button onClick={handleButtonClick}>Action</button>
</div>
);
}
Inline vs Named Handlers
// Named — preferred for complex logic
<button onClick={handleClick}>Click</button>
// Inline — OK for simple cases
<button onClick={() => setCount(c => c + 1)}>+</button>
// Avoid creating new functions in render for lists (performance)
// Bad in large lists:
items.map(item => <Item key={item.id} onClick={() => handle(item.id)} />)
Pass event handlers as props to child components for reusable, testable UI.