React Portals: How They Work and When to Use Them for Modals and Tooltips
You’ve probably built a modal or tooltip in React and hit a weird snag: the overlay appears visually outside your usual component tree, but events don’t behave as you expect. Maybe clicks inside the modal don’t bubble the way you thought, or keyboard focus seems lost when you open it. That’s React portals messing with your head , in a good way. They let you render children into a DOM node outside…
React portals are a powerful tool for rendering components outside their normal position in the React DOM tree. This can prevent clipping issues, improve stacking order, and make focus management easier for modals, tooltips and other overlay components.
Under the hood, a portal lets React render its children into a separate DOM node that lives outside the root React container. This means the component tree and the actual DOM tree can diverge - the modal or tooltip will be rendered as a real DOM node at the specified container location like document.body, while the React tree still sees it as a child of the root component.
This separation affects how React handles events and focus. Events bubble and propagate through the real DOM, but the portal nodes are separate from the React tree. So clicking inside a portalized modal may not trigger event handlers as expected if they are listening at the React root level rather than the portal container. Focus management also breaks down, because keyboard navigation works on the real DOM, not the React tree.
The key to using portals correctly is understanding these differences. Keep a ref to the portal container DOM node and check event targets against that container when handling clicks or keyboard events. Attach event listeners to the portal container instead of the React root. Explicitly manage focus by focusing the first focusable element inside the portal and trapping tab navigation inside the portal container.
And watch out for CSS stacking context and overflow issues that can affect portalized elements. Portals are ideal when you need UI overlays that break out of their parent containers' clipping, need to be siblings of the main app node, or require independent focus management. Modals, tooltips, dropdowns and similar UI elements are common candidates for using portals to get them positioned and focused correctly.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.