Event Handling

⚛️ ReactLesson 4Beginner

React wraps native DOM events in SyntheticEvents for cross-browser consistency. Event handlers are passed as props using camelCase names.

1 Common Events
React — Event Handlers
function EventDemo() {
  // Mouse events
  const handleClick  = (e) => console.log("Clicked!", e.target);
  const handleHover  = ()  => console.log("Hovered!");

  // Keyboard events
  const handleKeyDown = (e) => {
    if (e.key === "Enter") console.log("Enter pressed");
    if (e.key === "Escape") console.log("Escape pressed");
  };

  // Form events
  const handleChange = (e) => console.log(e.target.value);
  const handleSubmit = (e) => {
    e.preventDefault(); // stop page reload
    console.log("Form submitted");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        onChange={handleChange}
        onKeyDown={handleKeyDown}
        placeholder="Type something..."
      />
      <button
        type="button"
        onClick={handleClick}
        onMouseEnter={handleHover}
      >
        Click Me
      </button>
    </form>
  );
}
2 Passing Arguments to Handlers
React — Event with Arguments
function ItemList({ items }) {
  const handleDelete = (id) => {
    console.log("Delete item:", id);
  };

  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>
          {item.name}
          {/* Arrow function wraps the call so we can pass id */}
          <button onClick={() => handleDelete(item.id)}>Delete</button>
        </li>
      ))}
    </ul>
  );
}
3 Code Challenge
Challenge: Build a color picker component. Render 5 colored buttons. When clicked, display the selected color name and update the background of a preview box to that color.