React Tutorial menu

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

jsx
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 thisWhat 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

jsx
<button onClick={() => alert("Saved")}>Save</button>

Passing Arguments

Wrap the call in an arrow function when you need to pass a value:

Example

jsx
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>
  );
}
Output
(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

jsx
function SearchBox() {
  function handleChange(event) {
    console.log("You typed:", event.target.value);
  }

  return <input type="text" onChange={handleChange} placeholder="Search books" />;
}
Output
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 propWhen it fires
onClickThe element is clicked
onChangeAn input, select or textarea value changes
onSubmitA form is submitted
onMouseEnterThe mouse moves over the element
onKeyDownA key is pressed
onFocus / onBlurAn 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

jsx
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

jsx
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?

Learn React with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp