React Portals render children into a DOM node outside the parent component's hierarchy while maintaining React's event bubbling.
Basic Portal#
Creating Portal Container#
Modal Component#
Tooltip Portal#
Event Bubbling#
Dropdown Portal#
Focus Management#
Context in Portals#
Multiple Portal Layers#
Best Practices#
When to Use Portals:
✓ Modals and dialogs
✓ Tooltips and popovers
✓ Dropdown menus
✓ Notifications/toasts
✓ Full-screen overlays
Accessibility:
✓ Use proper ARIA attributes
✓ Manage focus correctly
✓ Trap focus in modals
✓ Restore focus on close
Implementation:
✓ Clean up portal containers
✓ Handle scroll and resize
✓ Use z-index properly
✓ Consider keyboard navigation
Avoid:
✗ Overusing portals
✗ Breaking context unnecessarily
✗ Forgetting cleanup
✗ Ignoring accessibility
Conclusion#
React Portals enable rendering children outside the DOM hierarchy while preserving React's features like event bubbling and context. Use them for modals, tooltips, dropdowns, and any UI that needs to escape parent containers. Always manage focus properly, clean up portal containers, and maintain accessibility. Remember that events still bubble through the React component tree, not the DOM tree.