Reacting to Users: The Core of Interactivity
A React application without events is just a static page. Events are the bridge that connects your user's actions—clicks, key presses, form submissions—to your component's logic and state. Mastering event handling is the single most important step toward building dynamic, interactive web applications.
In React, handling events is very similar to handling events on DOM elements, but with a few key differences:
- **camelCase:** React event names are camelCased (
onClick) instead of lowercase (onclick). - **Functions, Not Strings:** You pass a function as the event handler (
onClick={handleClick}) rather than a string (onclick="handleClick()").
1. The Click Event: `onClick`
The most basic event. You can add it to almost any JSX element, but it's most commonly used on buttons.
function MyButton() {
function handleClick() {
alert('You clicked me!');
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}Notice we pass `handleClick`, **not** `handleClick()`. If you include the parentheses, the function will execute **when the component renders**, not when the button is clicked. This is a very common mistake.
2. The Change Event: `onChange` and Controlled Components
This is the most critical concept for forms. A **controlled component** is an input element (like `<input>`) whose value is controlled by React state.
The "control loop" works like this:
- The input's `value` prop is set to a variable from `useState`.
- The user types a character.
- The `onChange` event fires.
- The event handler function is called.
- Inside the handler, we use `event.target.value` to get the new text.
- We call the state's setter function (e.g., `setText`) with this new text.
- React re-renders the component.
- The input's `value` is now updated from the state, showing the new character.
function NameForm() {
const [name, setName] = useState('');
function handleChange(event) {
// 'event.target.value' contains the current text in the input
setName(event.target.value);
}
return (
<>
<input value={name} onChange={handleChange} />
<p>Your name is: {name}</p>
</>
);
}3. The Submit Event: `onSubmit`
To handle form submissions, you should always use the `onSubmit` event on the `<form>` tag itself, not an `onClick` on the submit button. This ensures the form submits even if the user hits "Enter" on their keyboard.
The most important part of `onSubmit` is calling `event.preventDefault()`. By default, submitting a form causes the browser to reload the entire page. `preventDefault()` stops this behavior, allowing you to handle the submission with JavaScript and React state.
function MyForm() {
const [name, setName] = useState('');
function handleSubmit(event) {
// This is ESSENTIAL!
event.preventDefault();
alert('A name was submitted: ' + name);
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input value={name} onChange={(e) => setName(e.target.value)} />
</label>
<button type="submit">Submit</button>
</form>
);
}4. Passing Arguments to Handlers
What if you have a list of items and need to know *which* one was clicked? You can't just write `onClick={handleClick(item.id)}`. Instead, you use an inline arrow function:
function ItemList({ items }) {
function handleItemClick(id) {
console.log('Clicked item with id:', id);
}
return (
<ul>
{items.map(item => (
<li key={item.id} onClick={() => handleItemClick(item.id)}>
{item.name}
</li>
))}
</ul>
);
}Here, `onClick` is given an arrow function. That function is *not* called until the click happens. When it *is* called, it then executes your `handleItemClick` function with the correct `id`.
Key Takeaway: React's event system is all about managing state. User actions trigger events, events call handler functions, and handler functions update the state. This one-way data flow is the heart of React.