React Events
React lets your components respond to user actions such as clicks, typing and form submits.
Adding an Event Handler
Pass a function to an event prop such as onClick. Event names use camelCase.
Example
function OrderButton() {
function handleClick() {
alert("Your order has been placed!");
}
return <button onClick={handleClick}>Place Order</button>;
}When the user clicks the button, React calls handleClick.
Notice there are no brackets after the name: onClick={handleClick}. If you write onClick={handleClick()}, the function runs straight away while rendering, not on click.
| Write this | What happens |
|---|---|
onClick={handleClick} | Runs when clicked (correct) |
onClick={handleClick()} | Runs immediately during render (wrong) |
onClick={() => handleClick()} | Runs when clicked (correct) |
Inline Arrow Functions
For short handlers, you can write an arrow function directly:
Example
<button onClick={() => alert("Saved")}>Save</button>Passing Arguments
Wrap the call in an arrow function when you need to pass a value:
Example
function SizePicker() {
function chooseSize(size) {
alert("You chose size " + size);
}
return (
<div>
<button onClick={() => chooseSize("S")}>Small</button>
<button onClick={() => chooseSize("M")}>Medium</button>
<button onClick={() => chooseSize("L")}>Large</button>
</div>
);
}(after clicking Medium) You chose size M
The Event Object
React passes an event object to your handler. It tells you what happened and where.
Example
function SearchBox() {
function handleChange(event) {
console.log("You typed:", event.target.value);
}
return <input type="text" onChange={handleChange} placeholder="Search books" />;
}You typed: H You typed: Ha You typed: Har
event.target is the element that fired the event, so event.target.value is the text in the input.
Common Events
| Event prop | When it fires |
|---|---|
onClick | The element is clicked |
onChange | An input, select or textarea value changes |
onSubmit | A form is submitted |
onMouseEnter | The mouse moves over the element |
onKeyDown | A key is pressed |
onFocus / onBlur | An input gets or loses focus |
Stopping Default Behaviour
Some elements have default actions. A form, for example, reloads the page when submitted. Call event.preventDefault() to stop that:
Example
function ContactForm() {
function handleSubmit(event) {
event.preventDefault();
alert("Thank you! We will call you soon.");
}
return (
<form onSubmit={handleSubmit}>
<input type="tel" placeholder="Phone number" />
<button type="submit">Send</button>
</form>
);
}Passing Handlers as Props
A parent can pass a function to a child. The child calls it when something happens. By convention these props start with on.
Example
function AddButton({ onAdd, label }) {
return <button onClick={onAdd}>{label}</button>;
}
function Cart() {
function addToCart() {
alert("Added to cart");
}
return <AddButton label="Add Mouse" onAdd={addToCart} />;
}This is how child components "talk back" to their parents.
Event handlers are the right place for side effects like showing alerts, sending data or changing state. Do not do these things directly in the component body.
So far our handlers only show alerts. To change what is on the screen, you need state, which you will learn in the useState lesson.
Exercise
Exercise
Which line correctly runs sayHello only when the button is clicked?
