πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Advanced Portal Patterns

React Patterns🟒 Free Lesson

Advertisement

Advanced Portal Patterns

Nested portals, event delegation, z-index management, and focus trapping.

Overview

Portals enable rendering outside the DOM hierarchy while maintaining React context.

Key Concepts

  • Portal Containers β€” Multiple portal roots for different z-levels
  • Event Delegation β€” Handle events across portal boundaries
  • Z-Index Management β€” Prevent portal stacking issues
  • Focus Trapping β€” Keep focus within modal portals
  • SSR Compatibility β€” Handle server-side rendering gracefully

Code Examples

// Portal container management
function PortalProvider({ children }) {
  const [portals, setPortals] = useState([]);
  const [nextId, setNextId] = useState(0);

  const createPortal = useCallback((content, options = {}) => {
    const id = nextId;
    setNextId(n => n + 1);
    setPortals(prev => [...prev, { id, content, ...options }]);
    return () => setPortals(prev => prev.filter(p => p.id !== id));
  }, [nextId]);

  return (
    <PortalContext.Provider value={createPortal}>
      {children}
      {portals.map(portal => createPortal(portal.content, portal.containerId))}
    </PortalContext.Provider>
  );
}

// Focus trap for modals
function useFocusTrap(ref) {
  useEffect(() => {
    if (!ref.current) return;
    
    const focusableElements = ref.current.querySelectorAll(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    );
    const firstElement = focusableElements[0];
    const lastElement = focusableElements[focusableElements.length - 1];

    const handleKeyDown = (e) => {
      if (e.key !== 'Tab') return;
      
      if (e.shiftKey) {
        if (document.activeElement === firstElement) {
          lastElement.focus();
          e.preventDefault();
        }
      } else {
        if (document.activeElement === lastElement) {
          firstElement.focus();
          e.preventDefault();
        }
      }
    };

    ref.current.addEventListener('keydown', handleKeyDown);
    firstElement?.focus();
    
    return () => ref.current?.removeEventListener('keydown', handleKeyDown);
  }, [ref]);
}

Practice

Build a toast notification system with portal management and focus handling.

⭐

Premium Content

Advanced Portal Patterns

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement