Sub topic 3
Context, Accessibility, and Testing with React Portals
Assume you know function components, JSX, props, useState, useEffect, basic DOM concepts, and CSS positioning.
Context and state still flow through portals
A portal changes the DOM location, not the React location. The portal child remains under its original React parent. Therefore, it can read context, use state, and receive props as usual.
import { createPortal } from 'react-dom';
function ThemeProvider({ children }) {
return <div>{children}</div>;
}
function Menu({ theme }) {
return createPortal(
<div className={theme}>Menu content</div>,
document.body
);
}State is also preserved while the component keeps the same React position and key. Events can bubble to React ancestors even when the DOM nodes are far apart.
Accessibility: roles, focus and Escape
A modal should use role="dialog" and aria-modal="true". Give it an accessible name with aria-labelledby or aria-label. Move focus into the dialog when it opens, keep focus inside while it is active, and restore focus to the triggering element when it closes.
Listen for Escape in an effect and remove the listener during cleanup. Without cleanup, closed dialogs can leave stray listeners behind.
Tooltips and popovers
Portals help tooltips and popovers escape clipping and stacking contexts. A tooltip gives information and commonly connects to its trigger with aria-describedby. A popover usually contains interactive controls, so its trigger needs clear keyboard behavior and an appropriate relationship. Position the overlay from the trigger's measured viewport coordinates.
Portals and server rendering
document does not exist during server rendering. Look up the container in useEffect, then render the portal only after the client mounts. This prevents server errors and hydration mismatches.
Testing portal content
Testing Library's screen queries search document.body, so they can find portal content:
const { container } = render(<Modal>Hello</Modal>);
expect(screen.getByRole('dialog')).toHaveTextContent('Hello');
expect(container).not.toContainElement(screen.getByRole('dialog'));Pitfalls and best practices
- Ensure the portal container exists, or create and remove a dedicated container deliberately.
- Clean up document listeners and dynamically created nodes.
- Avoid using a portal when ordinary layout can solve the problem.
- Stop backdrop clicks from closing the dialog when the click originated inside it.
- Keep modal state in a predictable owner, and test keyboard behavior.
Exercise
Does a portal child lose access to its parent’s context?
Show answer
No. It remains in the same React tree, so context, props, state, and React event propagation continue to work.