React Lesson 8: Event Handling

⚛️ React CourseLesson 8 of 15 · 53% complete

React handles events similarly to HTML but with camelCase names and functions (not strings). Understanding events is essential for interactive UIs.

Basic Events

function App() {
  const handleClick = () => {
    console.log("Clicked!");
  };
  
  const handleMouseOver = () => {
    console.log("Mouse over!");
  };
  
  return (
    <div>
      <button onClick={handleClick}>Click</button>
      <div onMouseOver={handleMouseOver}>Hover me</div>
    </div>
  );
}

// Common events:
// onClick, onDoubleClick, onChange, onSubmit,
// onKeyDown, onKeyUp, onMouseOver, onMouseOut,
// onFocus, onBlur, onScroll

Event Object

function Form() {
  const handleChange = (event) => {
    console.log(event.target.value);  // current input value
    console.log(event.target.name);   // input name attribute
    console.log(event.target.type);   // input type
  };
  
  const handleSubmit = (event) => {
    event.preventDefault();  // IMPORTANT! Stops page reload
    console.log("Form submitted!");
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <input name="email" onChange={handleChange} />
      <button type="submit">Submit</button>
    </form>
  );
}

Passing Arguments to Event Handlers

function TodoList() {
  const items = ["Buy groceries", "Go to gym", "Learn React"];
  
  const handleDelete = (index) => {
    console.log(`Delete item at index ${index}`);
  };
  
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>
          {item}
          {/* Arrow function to pass argument */}
          <button onClick={() => handleDelete(index)}>Delete</button>
        </li>
      ))}
    </ul>
  );
}

🏋️ Practice Task

Build a color picker. Have 5 colored buttons (red, green, blue, purple, orange). When clicked, change the background color of a big preview div to that color. Show the current color name as text.

💡 Hint: const [color, setColor] = useState(“white”). Each button: onClick={() => setColor(“red”)}. Apply:

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *