Advertisement
Intermediate React, Portals & Fragments

How do event bubbling and Portals interact with each other in React?

Short answer

Even though a Portal's content is placed elsewhere in the actual HTML, React still treats click and other events as if they bubble up through the normal component tree, not through the actual physical HTML location.

Save React mock interview
Advertisement
AModel answer
Even though a Portal's content is placed elsewhere in the actual HTML, React still treats click and other events as if they bubble up through the normal component tree, not through the actual physical HTML location. This means a click inside a Portal can still be caught by an event handler higher up in your React component structure.
function App() {
  return (
    <div onClick={() => console.log('Parent clicked')}>
      <Modal>
        <button onClick={() => console.log('Button clicked')}>Click Me</button>
      </Modal>
    </div>
  );
}
// Clicking the button logs both messages, even though the modal renders elsewhere in the HTML
Real-world example
A dropdown menu rendered through a Portal still correctly closes when a click is detected on an outer wrapping div, because React's event bubbling follows the component tree rather than the actual visual location on the page.
Likely follow-ups
  • Why does this behavior sometimes surprise developers who expect events to follow the physical HTML structure instead?
  • How would you detect a click outside of a Portal's content specifically?
Related topics