⚛️ React Events

Chapter 8 of 15

React Events

Just like HTML, React can perform actions based on user events. React has the same events as HTML: click, change, mouseover, etc.

💡 Key Difference: React events are named using camelCase, rather than lowercase. With JSX you pass a function as the event handler, rather than a string.

Adding Events

React events are written in camelCase syntax:

HTML Example:

<button onclick="shoot()">Take the shot!</button>

React Example:

<button onClick={shoot}>Take the shot!</button>

Event Handlers

Here's a simple example of a button click event:

function Football() {
  const shoot = () => {
    alert("Great Shot!");
  }

  return (
    <button onClick={shoot}>Take the shot!</button>
  );
}
✨ Note: Pass the function name without parentheses! onClick={shoot} not onClick={shoot()}

Passing Arguments

To pass an argument to an event handler, use an arrow function:

function Football() {
  const shoot = (a) => {
    alert(a);
  }

  return (
    <button onClick={() => shoot("Goal!")}>
      Take the shot!
    </button>
  );
}

React Event Object

Event handlers have access to the React event that triggered the function:

function Football() {
  const shoot = (a, b) => {
    alert(b.type);
    // 'b' represents the React event
    // In this case, the 'click' event
  }

  return (
    <button onClick={(event) => shoot("Goal!", event)}>
      Take the shot!
    </button>
  );
}

Common Event Types

Mouse Events

function MouseEvents() {
  const handleClick = () => console.log("Clicked!");
  const handleHover = () => console.log("Hovering!");

  return (
    <button 
      onClick={handleClick}
      onMouseEnter={handleHover}
    >
      Hover or Click Me
    </button>
  );
}

Keyboard Events

function KeyboardEvents() {
  const handleKeyPress = (event) => {
    console.log("Key pressed:", event.key);
  };

  return (
    <input 
      type="text"
      onKeyDown={handleKeyPress}
      placeholder="Type something..."
    />
  );
}

Form Events

function FormEvents() {
  const handleChange = (event) => {
    console.log("Value changed:", event.target.value);
  };

  const handleFocus = () => {
    console.log("Input focused");
  };

  return (
    <input
      type="text"
      onChange={handleChange}
      onFocus={handleFocus}
    />
  );
}

Event Handler with State

Combining events with state to create interactive components:

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  const handleIncrement = () => {
    setCount(count + 1);
  };

  const handleDecrement = () => {
    setCount(count - 1);
  };

  const handleReset = () => {
    setCount(0);
  };

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={handleIncrement}>+</button>
      <button onClick={handleDecrement}>-</button>
      <button onClick={handleReset}>Reset</button>
    </div>
  );
}

Preventing Default Behavior

Use event.preventDefault() to prevent default browser behavior:

function MyForm() {
  const handleSubmit = (event) => {
    event.preventDefault();  // Prevents page refresh
    console.log("Form submitted!");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" />
      <button type="submit">Submit</button>
    </form>
  );
}
⚠️ Important: In HTML, the default behavior of a form submit is to refresh the page. In React, we usually prevent this and handle the submission in JavaScript.

Event Pooling (Legacy)

In React 16 and earlier, events were pooled for performance. In React 17+, this is no longer the case:

// In React 17+, this works fine:
const handleClick = (event) => {
  setTimeout(() => {
    console.log(event.type);  // Works!
  }, 1000);
};

Inline Event Handlers

You can write event handlers inline, but it's not recommended for complex logic:

// Simple inline handler (OK for simple logic)
<button onClick={() => console.log("Clicked")}>
  Click Me
</button>

// Better: Define handler separately
const handleClick = () => {
  console.log("Clicked");
};

<button onClick={handleClick}>Click Me</button>

Multiple Events on One Element

You can attach multiple event handlers to a single element:

function MultipleEvents() {
  const handleClick = () => console.log("Clicked!");
  const handleMouseEnter = () => console.log("Mouse entered!");
  const handleMouseLeave = () => console.log("Mouse left!");

  return (
    <button
      onClick={handleClick}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      Hover and Click Me
    </button>
  );
}

Real-World Example: Toggle Button

import { useState } from "react";

function ToggleButton() {
  const [isOn, setIsOn] = useState(false);

  const handleToggle = () => {
    setIsOn(!isOn);
  };

  return (
    <div>
      <button 
        onClick={handleToggle}
        style={{
          backgroundColor: isOn ? "green" : "gray",
          color: "white",
          padding: "10px 20px"
        }}
      >
        {isOn ? "ON" : "OFF"}
      </button>
    </div>
  );
}

Real-World Example: Input with Live Feedback

import { useState } from "react";

function LiveInput() {
  const [text, setText] = useState("");

  const handleChange = (event) => {
    setText(event.target.value);
  };

  return (
    <div>
      <input
        type="text"
        value={text}
        onChange={handleChange}
        placeholder="Type something..."
      />
      <p>You typed: {text}</p>
      <p>Character count: {text.length}</p>
    </div>
  );
}

Event Handler Best Practices

💡 Naming Convention: It's common to prefix event handler functions with "handle" (e.g., handleClick, handleSubmit, handleChange).

What's Next?

Now that you understand events, you're ready to learn about Forms - how to handle user input in React applications!