JavaScript and React course ยท Module 3: State and Events

Event Propagation and Advanced Event Handling Patterns

6 min read ยท
In this lesson7

On board the React spaceship, events do not move in a vacuum - they travel through the component hierarchy, like an alarm signal that spreads from a sensor in the engine room all the way to the main command center. Understanding event propagation allows you to precisely control which component responds to the signal and when.

How events propagate in React

In the browser DOM, events go through three phases:

  1. Capture - the event descends from the document root down to the target element
  2. Target - the event reaches the element that was clicked
  3. Bubbling - the event travels back up, from the target element to the root

React handles events in the bubbling phase by default - meaning the event "bubbles" from child to parent. Imagine it like an alarm on a ship: the smoke detector in a cabin (target element) triggers, and the signal bubbles up - first the deck commander hears it, then the chief engineer, and finally the ship's captain.

function SpaceStation() {
  const handleStationClick = () => {
    console.log('3. Space Station: signal reached command center');
  };

  return (
    <div onClick={handleStationClick} style={{ padding: '40px', background: '#1a1a3e' }}>
      <h2>Space Station</h2>
      <Deck />
    </div>
  );
}

function Deck() {
  const handleDeckClick = () => {
    console.log('2. Deck: signal passing through deck');
  };

  return (
    <div onClick={handleDeckClick} style={{ padding: '30px', background: '#2a2a5e' }}>
      <p>Main Deck</p>
      <Cabin />
    </div>
  );
}

function Cabin() {
  const handleCabinClick = () => {
    console.log('1. Cabin: sensor activated!');
  };

  return (
    <button onClick={handleCabinClick}>
      Cabin Sensor
    </button>
  );
}

After clicking the "Cabin Sensor" button, the console will show:

  1. Cabin: sensor activated!
  2. Deck: signal passing through deck
  3. Space Station: signal reached command center

The event bubbles from child to parent - the exact opposite of what you might expect!

Stopping propagation - stopPropagation()

Sometimes you want the signal to not leave a given ship module. The e.stopPropagation() method stops bubbling:

function ControlPanel() {
  const handlePanelClick = () => {
    console.log('Panel: this will NOT be called');
  };

  return (
    <div onClick={handlePanelClick} style={{ padding: '20px' }}>
      <h3>Control Panel</h3>
      <EmergencyButton />
    </div>
  );
}

function EmergencyButton() {
  const handleEmergency = (e) => {
    e.stopPropagation(); // Stop propagation!
    console.log('Emergency button: signal captured locally');
  };

  return (
    <button onClick={handleEmergency}>
      Emergency Button
    </button>
  );
}

After clicking "Emergency Button", only the handleEmergency handler will be called - the event will not reach the parent ControlPanel.

Preventing default behavior - preventDefault()

In addition to stopPropagation() (stops bubbling), there is e.preventDefault() - which prevents the browser's default behavior. These two methods do completely different things:

MethodAction
e.stopPropagation()Stops bubbling to parent elements
e.preventDefault()Blocks the browser's default behavior (e.g., form submission)
function MissionForm() {
  const [missionName, setMissionName] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault(); // Prevent page reload!
    console.log('Mission submitted:', missionName);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={missionName}
        onChange={(e) => setMissionName(e.target.value)}
        placeholder="Mission name"
      />
      <button type="submit">Submit Mission</button>
    </form>
  );
}

Without e.preventDefault(), the form would cause a page reload - the default browser behavior for the <form> element.

Event Delegation

Event delegation is a pattern where a single handler on the parent handles events from all children. It is like one officer on the bridge handling all signals from individual sectors instead of assigning a separate officer to each sensor:

function CrewList() {
  const crew = [
    { id: 1, name: 'Captain Nova', role: 'Command' },
    { id: 2, name: 'Engineer Astro', role: 'Warp Drive' },
    { id: 3, name: 'Navigator Ra', role: 'Navigation' },
    { id: 4, name: 'Medic Luna', role: 'Medical Bay' },
  ];

  // One handler on the parent instead of one on each element
  const handleCrewClick = (e) => {
    const crewId = e.target.closest('[data-crew-id]')?.dataset.crewId;
    if (crewId) {
      const member = crew.find(c => c.id === Number(crewId));
      console.log('Selected crew member:', member.name);
    }
  };

  return (
    <ul onClick={handleCrewClick}>
      {crew.map(member => (
        <li key={member.id} data-crew-id={member.id}>
          {member.name} - {member.role}
        </li>
      ))}
    </ul>
  );
}

In plain JavaScript, delegation saves hundreds of separate listeners on large lists. React does this for you: since version 17 it attaches one listener per event type to the app's root, so onClick on 100 <li> elements does not create 100 DOM listeners. In React, delegation is therefore useful when one handler needs to recognise the clicked element (e.g. by a data-* attribute), not for performance.

Passing arguments to handlers

A common pattern is passing additional data to an event handler. You can wrap the call in an arrow function in JSX or prepare a function that returns a ready handler (currying):

function MissionSelector() {
  const missions = ['Apollo', 'Artemis', 'Voyager', 'Orion'];
  const [selected, setSelected] = useState(null);

  // Pattern: function returning a handler
  const handleSelect = (missionName) => () => {
    setSelected(missionName);
    console.log('Mission selected:', missionName);
  };

  // Alternatively, without currying: const selectMission = (missionName) => setSelected(missionName);
  // and in JSX: onClick={() => selectMission(mission)}

  return (
    <div>
      <h3>Select a Mission:</h3>
      {missions.map(mission => (
        <button key={mission} onClick={handleSelect(mission)}>
          {mission}
        </button>
      ))}
      {selected && <p>Active mission: {selected}</p>}
    </div>
  );
}

The const handleSelect = (arg) => () => {...} pattern (currying) is just another way to write the same thing: handleSelect(mission) also creates a new function for every button on every render, just like onClick={() => selectMission(mission)}. Pick whichever reads better to you - creating functions during render is normal in React and there is no need to avoid it.

Handling multiple events with a single handler

When a component handles multiple related events, you can use a single handler with differentiation by event.target.name or event.target.dataset:

function ShipControls() {
  const [systems, setSystems] = useState({
    engines: false,
    shields: false,
    weapons: false,
  });

  const handleToggle = (e) => {
    const systemName = e.target.name;
    setSystems(prev => ({
      ...prev,
      [systemName]: !prev[systemName]
    }));
  };

  return (
    <div>
      <h3>Ship Systems:</h3>
      {Object.entries(systems).map(([name, isActive]) => (
        <label key={name} style={{ display: 'block', margin: '8px 0' }}>
          <input
            type="checkbox"
            name={name}
            checked={isActive}
            onChange={handleToggle}
          />
          {name}: {isActive ? 'ACTIVE' : 'OFFLINE'}
        </label>
      ))}
    </div>
  );
}

Thanks to [systemName]: !prev[systemName] (computed property name), a single handler manages all checkboxes. The name attribute on the input identifies which system should be toggled.

Summary

Event propagation and advanced event handling patterns are key skills for a React ship pilot:

  1. Bubbling - events propagate from child to parent (default in React)
  2. stopPropagation() - stops propagation to parent elements
  3. preventDefault() - blocks the browser's default behavior (e.g., form submit)
  4. Event delegation - one handler on the parent instead of many on children
  5. Passing arguments to handlers - an arrow function in JSX or currying
  6. Computed property names - one handler for multiple related elements

Mastering these techniques will allow you to build precise interaction systems where every signal on the ship goes exactly where it should!

Code for this lesson: App.jsx
import React, { useState } from 'react';

function EventLog({ logs }) {
  return (
    <div style={{
      background: '#0d1117', borderRadius: '8px', padding: '12px',
      maxHeight: '120px', overflowY: 'auto', fontFamily: 'monospace', fontSize: '12px'
    }}>
      <div style={{ color: '#8b949e', marginBottom: '4px' }}>Event console:</div>
      {logs.length === 0 && <div style={{ color: '#484f58' }}>Click elements to see propagation...</div>}
      {logs.map((log, i) => (
        <div key={i} style={{ color: log.color, padding: '2px 0' }}>
          {log.text}
        </div>
      ))}
    </div>
  );
}

function SpaceStation() {
  const [logs, setLogs] = useState([]);
  const [stopPropagation, setStopPropagation] = useState(false);

  const addLog = (text, color) => {
    setLogs(prev => [...prev, { text, color }]);
  };

  const handleStationClick = () => {
    addLog('3. Space station: signal reached command center', '#f39c12');
  };

  const handleDeckClick = (e) => {
    addLog('2. Main deck: signal passes through the deck', '#3498db');
  };

  const handleCabinClick = (e) => {
    if (stopPropagation) {
      e.stopPropagation();
      addLog('1. Cabin: signal STOPPED (stopPropagation)', '#e74c3c');
    } else {
      addLog('1. Cabin: sensor activated!', '#2ecc71');
    }
  };

  const handleClear = (e) => {
    e.stopPropagation();
    setLogs([]);
  };

  const styles = {
    container: { background: '#0a0e1a', color: '#e0e8ff', fontFamily: 'sans-serif', padding: '20px', minHeight: '100vh' },
    title: { color: '#4fc3f7', fontSize: '18px', marginBottom: '16px', textAlign: 'center' },
    station: { background: '#1a1a3e', borderRadius: '12px', padding: '20px', border: '2px solid #4fc3f7', cursor: 'pointer' },
    deck: { background: '#2a2a5e', borderRadius: '8px', padding: '16px', marginTop: '12px', border: '1px solid #6c6cae', cursor: 'pointer' },
    cabin: {
      display: 'block', width: '100%', marginTop: '12px', padding: '12px',
      background: '#27ae60', color: 'white', border: 'none', borderRadius: '6px',
      fontSize: '14px', cursor: 'pointer', fontWeight: 'bold'
    },
    toggle: {
      display: 'flex', alignItems: 'center', gap: '8px',
      margin: '16px 0', padding: '10px', background: '#1a2035', borderRadius: '6px'
    },
    clearBtn: {
      background: '#333', color: '#aaa', border: '1px solid #555', borderRadius: '4px',
      padding: '4px 12px', cursor: 'pointer', fontSize: '12px', marginTop: '8px'
    }
  };

  return (
    <div style={styles.container}>
      <h2 style={styles.title}>Event Propagation in React</h2>

      <label style={styles.toggle}>
        <input type="checkbox" checked={stopPropagation} onChange={() => setStopPropagation(prev => !prev)} />
        <span style={{ color: stopPropagation ? '#e74c3c' : '#aaa' }}>
          stopPropagation() {stopPropagation ? 'ACTIVE' : 'disabled'}
        </span>
      </label>

      <div style={styles.station} onClick={handleStationClick}>
        <div style={{ color: '#f39c12', fontSize: '12px' }}>onClick: Space Station</div>
        <div style={styles.deck} onClick={handleDeckClick}>
          <div style={{ color: '#3498db', fontSize: '12px' }}>onClick: Main Deck</div>
          <button style={styles.cabin} onClick={handleCabinClick}>
            Click: Sensor in the cabin
          </button>
        </div>
      </div>

      <div style={{ marginTop: '16px' }}>
        <EventLog logs={logs} />
        <button style={styles.clearBtn} onClick={handleClear}>Clear console</button>
      </div>
    </div>
  );
}

export default function App() {
  return <SpaceStation />;
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. In what order are onClick handlers called when clicking a nested element in React (by default)?

  2. 2. What is the difference between e.stopPropagation() and e.preventDefault()?

Hands-on tasks in the game

  • Code editor

    Create 3 boolean states: [lifeSupport, setLifeSupport] = useState(true), [powerGrid, setPowerGrid] = useState(true) and [communication, setCommunication] = useState(false). For each system add a button that toggles its state (prev => !prev) and display the status, e.g. Life Support: {lifeSupport ? 'ON' : 'OFF'}. The status colour depends on the state: green for ON, red for OFF.

  • Vertical ordering

    Arrange the phases of event propagation in the browser from start to finish:

  • Horizontal ordering

    Arrange the syntax for stopping event propagation in React:

  • Code editor

    Create a MissionProtocols component and render it in App. Keep an array of protocols { id, text, done } in state. A controlled text field and an Add button add a new protocol (a new array with spread). Each protocol has a checkbox that toggles done (map) and a Delete button that removes only that protocol (filter). Highlight completed protocols with a style, e.g. textDecoration: 'line-through'.

  1. QuestionEvent Propagation in React
  2. QuestionstopPropagation vs preventDefault
  3. Coding taskPractice: Toggle Switch
  4. Put in orderEvent Propagation Phases in the DOM
  5. Put in orderStopping Event Propagation
  6. Coding taskPractice: Todo List

Useful articles