Event Handling in React
Event handling is how React responds to user actions such as clicking a button, typing in an input field, hovering over an element, or submitting a form. React's event system is built on top of standard browser events, but it uses a consistent, cross-browser approach.
If a regular HTML button uses onclick, React uses onClick — the same concept, but written in camelCase and attached as a JSX attribute.
Basic Click Event
The most common event is a click. An event handler is a function that runs when the event occurs. It is attached to an element using a JSX attribute:
function ClickButton() {
function handleClick() {
alert("Button was clicked!");
}
return <button onClick={handleClick}>Click Me</button>;
}
Notice that handleClick is passed without parentheses: {handleClick}, not {handleClick()}. Passing with parentheses would call the function immediately when the component renders, not when the button is clicked.
Using Arrow Functions in Event Handlers
Arrow functions can also be used inline when a short action is needed:
function ClickButton() {
return (
<button onClick={() => alert("Clicked!")}>
Click Me
</button>
);
}
This approach works well for simple one-line actions. For anything more complex, it is better to define a named function outside the JSX to keep the code readable.
Common Event Types in React
React supports all standard browser events. Here are the most frequently used ones:
onClick— Fires when an element is clickedonChange— Fires when an input value changesonSubmit— Fires when a form is submittedonMouseEnter— Fires when the mouse enters an elementonMouseLeave— Fires when the mouse leaves an elementonKeyDown— Fires when a keyboard key is pressedonKeyUp— Fires when a keyboard key is releasedonFocus— Fires when an element receives focusonBlur— Fires when an element loses focus
The Event Object
When an event fires, React automatically passes an event object to the handler function. This object contains details about the event, such as which key was pressed or what the current value of an input is:
function InputTracker() {
function handleChange(event) {
console.log("Current value:", event.target.value);
}
return <input type="text" onChange={handleChange} />;
}
event.target refers to the HTML element that triggered the event. event.target.value gives the current text typed in the input field.
Combining Events with State
Events become truly useful when combined with state. Here is a live text input that displays what is being typed:
import { useState } from 'react';
function LiveInput() {
const [text, setText] = useState("");
function handleChange(event) {
setText(event.target.value);
}
return (
<div>
<input type="text" onChange={handleChange} placeholder="Type something..." />
<p>You typed: {text}</p>
</div>
);
}
Every time the user types a character, handleChange fires, updates the state with the new value, and React re-renders the paragraph to display the current input.
Passing Arguments to Event Handlers
If an event handler needs additional arguments besides the event object, wrap it in an arrow function:
function ColorPicker() {
function handleColorClick(color) {
alert(`You selected: ${color}`);
}
return (
<div>
<button onClick={() => handleColorClick("Red")}>Red</button>
<button onClick={() => handleColorClick("Blue")}>Blue</button>
<button onClick={() => handleColorClick("Green")}>Green</button>
</div>
);
}
Each button calls the same function with a different argument. The arrow function () => handleColorClick("Red") delays the call until the button is actually clicked.
Preventing Default Browser Behavior
Some HTML elements have built-in default behaviors. For example, clicking a link navigates to another page, and submitting a form refreshes the page. In React, event.preventDefault() stops these defaults:
function LoginForm() {
function handleSubmit(event) {
event.preventDefault(); // Prevents page reload
console.log("Form submitted!");
}
return (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Username" />
<button type="submit">Log In</button>
</form>
);
}
Without event.preventDefault(), the page would reload when the form is submitted, resetting all state and component data.
Mouse Hover Events
import { useState } from 'react';
function HoverBox() {
const [isHovered, setIsHovered] = useState(false);
return (
<div
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
{isHovered ? "Mouse is over me!" : "Hover over me"}
</div>
);
}
This example tracks whether the mouse is hovering over the element and updates the displayed text accordingly.
Key Points
- React events are written in camelCase:
onClick,onChange,onSubmit, etc. - Event handlers are functions passed as JSX attribute values — without parentheses.
- React passes an event object to handler functions automatically.
- Use
event.target.valueto read the current value of an input field. - Wrap handlers in arrow functions when passing additional arguments.
- Use
event.preventDefault()to stop default browser behaviors like form submission reloads. - Events and state work together to create interactive, dynamic user interfaces.
The next topic covers Conditional Rendering — how to show or hide parts of the UI based on conditions and state values.
