React Portals render children into a different DOM node while preserving React's component hierarchy. Here's how to use them.
Basic Portal#
Portal Container Hook#
Modal with Overlay#
Tooltip Portal#
Dropdown Portal#
Toast Notifications#
Focus Trap#
Event Bubbling#
SSR Considerations#
Best Practices#
Use Cases:
✓ Modals and dialogs
✓ Tooltips and popovers
✓ Dropdown menus
✓ Toast notifications
Accessibility:
✓ Implement focus trapping
✓ Add ARIA attributes
✓ Handle keyboard navigation
✓ Manage focus on open/close
Styling:
✓ Use fixed positioning
✓ Handle z-index properly
✓ Consider scroll locking
✓ Position relative to trigger
Avoid:
✗ Overusing portals
✗ Breaking accessibility
✗ Memory leaks (cleanup)
✗ Ignoring SSR
Conclusion#
React Portals render content outside the DOM hierarchy while maintaining React context and event bubbling. Use them for modals, tooltips, dropdowns, and any UI that needs to break out of container overflow or z-index constraints. Always implement proper accessibility with focus management, keyboard handling, and ARIA attributes. Handle SSR by checking for document availability before rendering.