React Events

React Events

React uses Synthetic Events โ€” a cross-browser wrapper around native browser events. They follow the W3C standard and behave identically in all browsers. Event names use camelCase (onClick, onChange, onSubmit).

Common Event Handlers

function EventShowcase() {
  // The event handler receives a SyntheticEvent object
  const handleClick    = (e) => console.log("Clicked", e.target);
  const handleChange   = (e) => console.log("Value:", e.target.value);
  const handleSubmit   = (e) => { e.preventDefault(); /* submit logic */ };
  const handleKeyDown  = (e) => { if (e.key === "Enter") submit(); };
  const handleMouseEnter = () => console.log("Hovered");

  return (
    <form onSubmit={handleSubmit}>
      <input
        onChange={handleChange}
        onKeyDown={handleKeyDown}
        onFocus={() => console.log("Focused")}
        onBlur={() => console.log("Blurred")}
      />
      <div
        onClick={handleClick}
        onMouseEnter={handleMouseEnter}
      >
        Click or hover
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

Passing Arguments to Handlers

function ItemList({ items }) {
  const handleDelete = (id) => {
    console.log("Delete item", id);
  };

  const handleEdit = (id, name) => {
    console.log("Edit", id, name);
  };

  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>
          {item.name}
          {/* Wrap in arrow function to pass arguments */}
          <button onClick={() => handleDelete(item.id)}>Delete</button>
          <button onClick={() => handleEdit(item.id, item.name)}>Edit</button>
        </li>
      ))}
    </ul>
  );
}

Event Propagation (Bubbling)

function BubbleDemo() {
  return (
    <div onClick={() => console.log("outer clicked")}>
      <button
        onClick={(e) => {
          e.stopPropagation(); // Prevent outer div from also firing
          console.log("button clicked");
        }}
      >
        Click me
      </button>
    </div>
  );
}
TipName event handler props with the on prefix (onClick, onClose, onAddToCart). Name your handler functions with handle (handleClick, handleClose). This convention makes the data flow obvious.

๐Ÿง  Test Yourself

What method prevents a form from reloading the page on submit?