🔥 0
0
Lesson 5 of 9 15 min +75 XP

Event Handling

React makes handling user interactions straightforward. Events in React work similarly to DOM events but with some syntactic differences.

Basic Event Handling

function Button() {
  const handleClick = () => {
    alert('Button clicked!');
  };

  return (
    <button onClick={handleClick}>
      Click me
    </button>
  );
}

Inline Handlers

For simple cases, you can define handlers inline:

<button onClick={() => console.log('Clicked!')}>
  Click me
</button>

React vs HTML Events

HTMLReact
onclickonClick
onchangeonChange
onsubmitonSubmit
String: "handleClick()"Function: {handleClick}

The Event Object

React passes a SyntheticEvent to your handler - a cross-browser wrapper around the native event:

function Input() {
  const handleChange = (event) => {
    console.log(event.target.value);  // Input value
    console.log(event.target.name);   // Input name
    console.log(event.type);          // Event type
  };

  return (
    <input
      name="username"
      onChange={handleChange}
    />
  );
}

Common Events

Click Events

<button onClick={handleClick}>Click</button>
<div onClick={handleDivClick}>Clickable div</div>

Form Events

<form onSubmit={handleSubmit}>
  <input onChange={handleChange} />
  <input onFocus={handleFocus} />
  <input onBlur={handleBlur} />
</form>

Keyboard Events

<input
  onKeyDown={(e) => {
    if (e.key === 'Enter') {
      handleSubmit();
    }
  }}
/>

Mouse Events

<div
  onMouseEnter={() => setHovered(true)}
  onMouseLeave={() => setHovered(false)}
>
  Hover me
</div>

Preventing Default Behavior

Use e.preventDefault() to stop the browser's default action:

function LoginForm() {
  const handleSubmit = (e) => {
    e.preventDefault();  // Stop page reload
    // Handle form submission
    console.log('Form submitted!');
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="email" name="email" />
      <input type="password" name="password" />
      <button type="submit">Login</button>
    </form>
  );
}

Passing Arguments to Handlers

Using Arrow Functions

function TodoList({ todos, onDelete }) {
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>
          {todo.text}
          <button onClick={() => onDelete(todo.id)}>
            Delete
          </button>
        </li>
      ))}
    </ul>
  );
}

Getting Event + Custom Arguments

const handleClick = (id, event) => {
  console.log('ID:', id);
  console.log('Event:', event.type);
};

<button onClick={(e) => handleClick(item.id, e)}>
  Click
</button>

Controlled Inputs

React can control form inputs through state:

function ControlledForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  return (
    <form>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email"
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Password"
      />
    </form>
  );
}

Event Handler Best Practices

1. Name Handlers Descriptively

// ✅ Clear what it does
const handleLoginSubmit = () => {};
const handleEmailChange = () => {};

// ❌ Too generic
const handleClick = () => {};
const handler = () => {};

2. Keep Handlers in the Component

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

  // Handler defined inside - has access to state
  const increment = () => setCount(count + 1);

  return <button onClick={increment}>+</button>;
}

3. Avoid Inline Functions for Complex Logic

// ❌ Hard to read
<button onClick={() => {
  validateForm();
  submitData();
  resetForm();
  showNotification();
}}>Submit</button>

// ✅ Cleaner
<button onClick={handleSubmit}>Submit</button>

Key Takeaways

  • Event names use camelCase: onClick, onChange, onSubmit
  • Pass functions, not function calls: onClick={handleClick}
  • Use e.preventDefault() to stop default browser behavior
  • Use arrow functions to pass arguments: onClick={() => fn(id)}
  • Controlled inputs have their value managed by React state

🧠 Quick Quiz

Test your understanding of this lesson.

1

How do you name event handlers in React?

2

What is e.preventDefault() used for?

3

How do you pass arguments to an event handler?

State with useState