Event Handling
onClick, onChange, synthetic events, preventing defaults, and bubbling
Skills taught: react.event-handlers, react.synthetic-events, react.event-propagation, react.controlled-inputs
Handling events in React
function ClickDemo() {
const [msg, setMsg] = useState('Click a button');
function handleSimpleClick() {
setMsg('Simple click!');
}
const handleWithData = (label) => {
setMsg(`Clicked: ${label}`);
};
return (
<div style={{ fontFamily: 'sans-serif', padding: '8px' }}>
<p>{msg}</p>
{/* Pass function reference — don't call it */}
<button onClick={handleSimpleClick}>Simple</button>
{/* Inline arrow function — use when you need to pass data */}
<button onClick={() => handleWithData('Alpha')}>Alpha</button>
<button onClick={() => handleWithData('Beta')}>Beta</button>
</div>
);
}
function InputDemo() {
const [value, setValue] = useState('');
const [submitted, setSubmitted] = useState('');
const handleSubmit = (e) => {
e.preventDefault(); // prevent page reload
setSubmitted(value);
setValue('');
};
return (
<form onSubmit={handleSubmit} style={{ display: 'flex', gap: '8px' }}>
<input
value={value}
onChange={e => setValue(e.target.value)} // e.target.value = current input
placeholder="Type something..."
style={{ padding: '6px', borderRadius: '4px', border: '1px solid #d1d5db' }}
/>
<button type="submit">Submit</button>
{submitted && <span>You sent: <strong>{submitted}</strong></span>}
</form>
);
}
function App() {
return (
<div style={{ fontFamily: 'sans-serif', padding: '8px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
<ClickDemo />
<InputDemo />
</div>
);
}
// Event bubbling — child events bubble to parent
function BubblingDemo() {
const [log, setLog] = useState([]);
const addLog = (msg) => setLog(prev => [...prev, msg]);
return (
<div
onClick={() => addLog('Outer div clicked')}
style={{ padding: '16px', border: '2px solid #4fd1c5', cursor: 'pointer' }}
>
Outer (click here too)
<div
onClick={() => addLog('Middle div clicked')}
style={{ margin: '8px', padding: '12px', border: '2px solid #f97316', cursor: 'pointer' }}
>
Middle
<button
onClick={(e) => {
e.stopPropagation(); // stops bubble — only button logs
addLog('Button clicked (stopped)');
}}
style={{ display: 'block', margin: '8px 0' }}
>
Button (stops propagation)
</button>
</div>
<ul style={{ fontSize: '0.8rem' }}>
{log.map((l, i) => <li key={i}>{l}</li>)}
</ul>
<button onClick={() => setLog([])} style={{ marginTop: '4px' }}>Clear</button>
</div>
);
}
function App() {
return <BubblingDemo />;
}
Frequently Asked Questions
How do I access the input value in an onChange handler?
Use e.target.value: <input onChange={e => setValue(e.target.value)} />. For checkboxes, it's e.target.checked. For select elements, it's also e.target.value (the value of the selected option). In TypeScript: (e: React.ChangeEvent<HTMLInputElement>) => e.target.value.