Events
An event is a user action: a click, typing, submitting a form. In React an event handler is passed to a component as an attribute, for example onClick — no addEventListener like in the DOM lessons.
A click handler
Create src/components/HelloButton.jsx:
// src/components/HelloButton.jsx
export default function HelloButton() {
function handleClick() {
alert('Hello!');
}
return <button onClick={handleClick}>Say hello</button>;
}Render <HelloButton /> in src/App.jsx and click the button — the browser shows a dialog with "Hello!". Handlers are usually named with the handle prefix: handleClick, handleSubmit.
An arrow function in the attribute
A short handler can be written in place:
// src/components/HelloButton.jsx
export default function HelloButton() {
return <button onClick={() => alert('Hello!')}>Say hello</button>;
}The result is the same. An arrow function is especially handy when the handler needs an argument.
A handler with an argument
Let every task have a button that reports which task was clicked:
// src/components/TodoItem.jsx
export default function TodoItem({ todo }) {
function handleDelete(id) {
console.log('Delete task', id);
}
return (
<li>
{todo.text}
<button onClick={() => handleDelete(todo.id)}>Delete</button>
</li>
);
}On click, the browser console (F12, the Console tab) shows, for example, "Delete task 2". The task cannot really be deleted yet — that needs state, from the next lesson.
The event object
A handler receives an event object. For an input field, the typed text is taken from it:
// src/components/SearchBox.jsx
export default function SearchBox() {
function handleChange(event) {
console.log(event.target.value);
}
return <input placeholder="Search" onChange={handleChange} />;
}Each keystroke prints the current text of the field to the console. In React onChange fires right while typing, not after leaving the field as in plain HTML.
Common events
| Attribute | When it fires |
|---|---|
onClick | A click on the element |
onChange | The value of a field changes |
onSubmit | A form is submitted |
onKeyDown | A key is pressed |
onMouseEnter | The mouse moves over the element |
onFocus, onBlur | A field gains or loses focus |
Cancelling the browser action
event.preventDefault() cancels the default behaviour: for example, following a link or reloading the page when a form is submitted. You will need it in the forms lesson.
Common mistake
The function must be passed, not called. Parentheses after the name run it right away during rendering:
// Wrong: the alert shows when the page loads, not on click.
<button onClick={handleClick()}>Say hello</button>
// Correct:
<button onClick={handleClick}>Say hello</button>
<button onClick={() => handleDelete(todo.id)}>Delete</button>If you need an argument, wrap the call in an arrow function.