Handling Events
Attach event handlers in JSX — onClick, onChange, onSubmit and the SyntheticEvent
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
React s use camelCase names and are passed as functions (not strings).
// HTML style — string (NOT how React works)
<button onclick="handleClick()">Click</button>
// React style — function reference
<button onClick={handleClick}>Click</button>
<button onClick={() => handleClick(id)}>Click</button>SyntheticEvent — React wraps native browser events in a cross-browser wrapper: ``jsx function SearchBar() { const handleChange = (event) => { console.log(event.target.value); // same API as native events }; return <input onChange={handleChange} />; }
Prevent default behavior:
jsx function Form() { const handleSubmit = (e) => { e.preventDefault(); // stop page reload // process form data }; return <form onSubmit={handleSubmit}> ... </form>; }
Passing arguments to handlers:
jsx // Arrow function wrapper — creates new function each render (fine for most cases) {items.map(item => ( <button key={item.id} onClick={() => deleteItem(item.id)}>Delete</button> ))}
Common React events: onClick, onChange, onSubmit, onKeyDown, onFocus, onBlur, onMouseEnter, onMouseLeave
Examples
Click counter with event object
The event object carries coordinates, keyboard state, target info, etc.
function ClickLogger() {
const [log, setLog] = useState([]);
const handleClick = (e) => {
const info = `Clicked at (${e.clientX}, ${e.clientY})`;
setLog(prev => [...prev, info]);
};
return (
<div>
<div className="clickable" onClick={handleClick}>Click anywhere here</div>
<ul>{log.map((entry, i) => <li key={i}>{entry}</li>)}</ul>
</div>
);
}Controlled form with submit
Combining onChange for controlled inputs with onSubmit for form handling
function LoginForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log('Login:', 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>
);
}How well did you understand this?
Next in React
Conditional Rendering