You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
React applications are interactive because components respond to user actions — clicks, key presses, form submissions, and more. React uses a synthetic event system that wraps the browser's native events, providing a consistent API across all browsers.
In React, event handlers are passed as props using camelCase names. You pass a function reference, not a function call:
function Button() {
function handleClick() {
alert("Button clicked!");
}
return <button onClick={handleClick}>Click me</button>;
}
The difference between onClick={handleClick} (correct — passes the function) and onClick={handleClick()} (wrong — calls it immediately during render) is critical.
For simple handlers or when you need to pass arguments, inline arrow functions work well:
function List({ items }) {
return (
<ul>
{items.map((item) => (
<li key={item.id} onClick={() => console.log(item.name)}>
{item.name}
</li>
))}
</ul>
);
}
React passes a SyntheticEvent object to every event handler. It has the same interface as the native browser event:
function TextInput() {
const [value, setValue] = useState("");
function handleChange(event) {
setValue(event.target.value);
}
return <input value={value} onChange={handleChange} />;
}
Common properties include event.target (the DOM element), event.target.value (for inputs), event.key (for keyboard events), and event.preventDefault() to stop default browser behaviour.
To prevent a form from submitting the page (the browser default), call event.preventDefault():
function LoginForm() {
function handleSubmit(event) {
event.preventDefault();
console.log("Form submitted");
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Log in</button>
</form>
);
}
React supports all standard DOM events:
Event handlers and state work together to create interactivity:
function Toggle() {
const [isOn, setIsOn] = useState(false);
return (
<button onClick={() => setIsOn(!isOn)}>
{isOn ? "ON" : "OFF"}
</button>
);
}
Every click toggles isOn, causing React to re-render the button with the updated label. This pattern — event triggers state update, state update triggers re-render — is the core loop of every interactive React application.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.