TExcelTAD
Home › React › React Events

React Events

Interactive apps respond to clicks, key presses, typing and more. In React you attach an event handler — a function — directly to the JSX element with a camelCase prop such as onClick or onChange.

Handling a click

jsx · try it yourself
export default function App() {
  function handleClick() {
    console.log('The button was clicked');
  }

  return <button onClick={handleClick}>Click me and watch the console</button>;
}

Pass the function itself — onClick={handleClick} — not the result of calling it. onClick={handleClick()} would run during rendering, every time the component renders.

✅ Correct ❌ Wrong Why
onClick={handleClick} onClick={handleClick()} the second calls it immediately
onClick={() => remove(id)} onClick={remove(id)} wrap calls with arguments in an arrow
onClick={handleClick} onclick="handleClick()" React uses camelCase props and functions

Passing arguments

When the handler needs extra information, wrap it in an arrow function:

jsx · try it yourself
import { useState } from 'react';

export default function App() {
  const [message, setMessage] = useState('Pick a size');

  function choose(size, price) {
    setMessage(`You chose ${size} for ${price}`);
  }

  return (
    <div>
      <button onClick={() => choose('Small', 3)}>Small</button>{' '}
      <button onClick={() => choose('Medium', 4)}>Medium</button>{' '}
      <button onClick={() => choose('Large', 5)}>Large</button>
      <p>{message}</p>
    </div>
  );
}

The event object

React passes a synthetic event to every handler. It wraps the browser's native event and works the same in all browsers. Common properties:

Property / method Meaning
e.target the element that triggered the event
e.currentTarget the element the handler is attached to
e.target.value current text of an input
e.key the key pressed ('Enter', 'a', …)
e.preventDefault() stops the browser's default action (e.g. form submit)
e.stopPropagation() stops the event bubbling to parent handlers
jsx · try it yourself
import { useState } from 'react';

export default function App() {
  const [log, setLog] = useState([]);

  function add(text) {
    setLog((prev) => [text, ...prev].slice(0, 6));
  }

  return (
    <div>
      <input
        placeholder="Type, then press Enter"
        onChange={(e) => add(`change: "${e.target.value}"`)}
        onKeyDown={(e) => e.key === 'Enter' && add('Enter pressed!')}
        onFocus={() => add('focus')}
        onBlur={() => add('blur')}
      />
      <div
        onMouseEnter={() => add('mouse entered the box')}
        onMouseLeave={() => add('mouse left the box')}
        style={{ margin: '12px 0', padding: 16, background: '#e8f4fd', width: 220 }}
      >
        Hover over me
      </div>
      <ol>{log.map((line, i) => <li key={i}>{line}</li>)}</ol>
    </div>
  );
}

Preventing default behaviour

A form submit normally reloads the page and a link normally navigates. Call e.preventDefault() to handle them yourself:

jsx · try it yourself
import { useState } from 'react';

export default function App() {
  const [result, setResult] = useState('');

  function handleSubmit(e) {
    e.preventDefault();
    const data = new FormData(e.currentTarget);
    setResult(`Searching for "${data.get('query')}"…`);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="query" placeholder="Search recipes" />
      <button type="submit">Search</button>
      <p>{result}</p>
    </form>
  );
}

Event propagation

Events bubble up from the element that was clicked through its ancestors. Here both handlers run when you click the button — unless the button stops propagation:

jsx · try it yourself
export default function App() {
  return (
    <div
      onClick={() => console.log('Card clicked → open details')}
      style={{ padding: 20, border: '1px solid #ccc', borderRadius: 8, width: 240, cursor: 'pointer' }}
    >
      <p>Product card</p>
      <button
        onClick={(e) => {
          e.stopPropagation();
          console.log('Added to cart (card handler skipped)');
        }}
      >
        Add to cart
      </button>
    </div>
  );
}

Naming conventions

  • Handler functions inside a component are usually named handleSomething: handleClick, handleSubmit.
  • Props that receive handlers are named onSomething: onSelect, onDelete.
jsx
function DeleteButton({ onDelete }) {
  return <button onClick={onDelete}>Delete</button>;
}

function Row({ item, removeItem }) {
  function handleDelete() {
    removeItem(item.id);
  }
  return <DeleteButton onDelete={handleDelete} />;
}

Tip: Event handlers are the right place for side effects — updating state, logging, sending requests. Unlike rendering, they don't need to be pure.

Test yourself

Which is the correct way to attach a click handler?

  1. onclick="save()"
  2. onClick={save()}
  3. onClick={save}
  4. click={save}

How do you call remove(id) when a button is clicked?

  1. onClick={remove(id)}
  2. onClick={() => remove(id)}
  3. onClick={remove, id}
  4. onClick="remove(id)"

What does e.preventDefault() do inside an onSubmit handler?

  1. Stops the event from bubbling
  2. Prevents the page reload caused by the form submission
  3. Clears the form
  4. Disables the submit button