React
Beginner
1 min read
Handling onClick and Synthetic Events
Example
import { useState } from 'react';
function EventDemo() {
const [log, setLog] = useState([]);
const addLog = (msg) => setLog(prev => [msg, ...prev].slice(0, 6));
// Plain handler reference
const handleClick = () => addLog('Button clicked');
// Handler that reads event properties
const handleMouseMove = (e) => {
addLog(`Mouse at (${e.clientX}, ${e.clientY})`);
};
// Handler with an argument — wrap in arrow function
const handleDelete = (id) => addLog(`Delete item #${id}`);
// Prevent default form submission
const handleSubmit = (e) => {
e.preventDefault();
addLog('Form submitted (default prevented)');
};
return (
<div>
<button onClick={handleClick}>Click me</button>
<div
style={{ width: 200, height: 60, background: '#f0f4f8', marginTop: 8 }}
onMouseMove={handleMouseMove}
>
Move mouse here
</div>
<div style={{ marginTop: 8 }}>
{[1, 2, 3].map(id => (
<button key={id} onClick={() => handleDelete(id)}>
Delete #{id}
</button>
))}
</div>
<form onSubmit={handleSubmit} style={{ marginTop: 8 }}>
<input type="text" placeholder="Type something" />
<button type="submit">Submit</button>
</form>
<ul style={{ marginTop: 8 }}>
{log.map((entry, i) => <li key={i}>{entry}</li>)}
</ul>
</div>
);
}
export default EventDemo;