React Portals render children outside the parent DOM hierarchy while maintaining React's event system. Here's how to use them.
What Are Portals?#
Why Use Portals?#
Modal Component#
Tooltip Component#
Notification Toast System#
Focus Management#
Custom Portal Container#
Event Bubbling#
SSR Considerations#
Best Practices#
Accessibility:
✓ Manage focus properly
✓ Use correct ARIA attributes
✓ Handle keyboard navigation
✓ Restore focus on close
Performance:
✓ Don't overuse portals
✓ Clean up portal containers
✓ Lazy load modal content
✓ Use CSS animations
Architecture:
✓ Create reusable portal hooks
✓ Manage z-index consistently
✓ Handle SSR properly
✓ Consider event bubbling
UX:
✓ Block body scroll in modals
✓ Handle click outside
✓ Provide escape key handling
✓ Animate enter/exit
Conclusion#
React Portals solve DOM hierarchy issues for modals, tooltips, and overlays. They maintain React's event system while rendering outside the parent. Use them when CSS constraints prevent proper rendering, always manage focus and accessibility, and handle SSR appropriately.