JavaScript and React course ยท Module 10: React Ecosystem and Future
React Portals - Rendering Outside the Hierarchy
In this lesson6
The communications module reports a failure and the message has to appear on the main screen of the bridge. The trouble is that the module sits in the cargo hold: its container has overflow: hidden and its own z-index, so the alarm window gets clipped or hides under other panels. React has a teleporter for this, the portal: the component stays in its place in the React tree, while its HTML materializes in a different DOM node.
What you will learn
- render a modal, a tooltip and a notification outside the parent's DOM,
- predict how events and context flow out of a portal,
- build modal, tooltip and notification systems,
- clean up after portals and take care of accessibility.
What Are React Portals?
The createPortal(children, domNode) function from the react-dom package takes two arguments: what to draw and in which existing DOM node. The simplest portal is a modal that lands in the #modal-root element instead of inside its parent:
import { createPortal } from 'react-dom';
function Modal({ children, isOpen }) {
if (!isOpen) return null;
// Render modal in #modal-root element instead of the current hierarchy
return createPortal(
<div className="modal-overlay">
<div className="modal-content">
{children}
</div>
</div>,
document.getElementById('modal-root') // Target DOM node
);
}
// In HTML there must exist:
// <div id="modal-root"></div>Modal is still a child of its parent in the React tree, only its place in the DOM changes. When isOpen is false, the portal is not created at all.
Why Use Portals?
Let's look at the problem: the container has overflow: hidden and its own z-index, so a regular modal will get clipped. The second function shows the emergency exit, a portal straight into document.body:
// Problem with normal rendering
function App() {
return (
<div style={{ position: 'relative', zIndex: 1, overflow: 'hidden' }}>
<Header />
<main>
{/* Modal might be clipped by overflow: hidden */}
<Modal>
<p>This modal might not be visible!</p>
</Modal>
</main>
</div>
);
}
// Solution with Portal
function PortalModal({ children, isOpen }) {
if (!isOpen) return null;
// Render directly in body - outside CSS constraints
return createPortal(
<div className="modal-backdrop">
<div className="modal">
{children}
</div>
</div>,
document.body
);
}PortalModal lands in body, so the CSS rules of its ancestors no longer restrict it. State, props and logic did not change.
Advanced Patterns
Portal Provider
When portals multiply, manage them from a single command center. PortalProvider keeps a map of portals in state and exposes addPortal and removePortal through context:
// PortalProvider.jsx
import { createContext, useContext, useState, useCallback } from 'react';
import { createPortal } from 'react-dom';
const PortalContext = createContext();
export function PortalProvider({ children }) {
const [portals, setPortals] = useState(new Map());
const addPortal = useCallback((id, content, target = document.body) => {
setPortals(prev => new Map(prev).set(id, { content, target }));
}, []);
const removePortal = useCallback((id) => {
setPortals(prev => {
const newMap = new Map(prev);
newMap.delete(id);
return newMap;
});
}, []);
return (
<PortalContext.Provider value={{ addPortal, removePortal }}>
{children}
{Array.from(portals.entries()).map(([id, { content, target }]) =>
createPortal(
<div data-portal-id={id}>
{content}
</div>,
target,
id // the portal's key in the list
)
)}
</PortalContext.Provider>
);
}
export const usePortal = () => {
const context = useContext(PortalContext);
if (!context) {
throw new Error('usePortal must be used within PortalProvider');
}
return context;
};Every map entry goes to its target through createPortal. new Map(prev) creates a new map instead of mutating the old one, because only a new reference signals a state change to React. The third, optional argument of createPortal is key: in a list of portals it lets React tell them apart, just like key on list elements.
The usePortal Hook
The usePortal hook creates the target node itself if it is missing and hands back a Portal component for wrapping content:
// usePortal.js
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
export function usePortal(id = 'portal') {
const [isClient, setIsClient] = useState(false);
const portalRef = useRef(null);
useEffect(() => {
setIsClient(true);
// Check if element already exists
let portalElement = document.getElementById(id);
// If it doesn't exist, create it
if (!portalElement) {
portalElement = document.createElement('div');
portalElement.id = id;
portalElement.setAttribute('data-portal', 'true');
portalElement.setAttribute('data-created-by-hook', 'true');
document.body.appendChild(portalElement);
}
portalRef.current = portalElement;
// Cleanup - remove element if it was created by this hook
return () => {
if (portalElement && portalElement.getAttribute('data-created-by-hook')) {
document.body.removeChild(portalElement);
}
};
}, [id]);
return {
Portal: ({ children }) => {
if (!isClient || !portalRef.current) return null;
return createPortal(children, portalRef.current);
},
portalElement: portalRef.current
};
}
// Usage
function MyComponent() {
const { Portal } = usePortal('my-custom-portal');
const [showModal, setShowModal] = useState(false);
return (
<div>
<button onClick={() => setShowModal(true)}>
Show modal
</button>
{showModal && (
<Portal>
<div className="modal-overlay" onClick={() => setShowModal(false)}>
<div className="modal-content" onClick={e => e.stopPropagation()}>
<h2>Modal via Portal</h2>
<button onClick={() => setShowModal(false)}>Close</button>
</div>
</div>
</Portal>
)}
</div>
);
}The node is created in useEffect, so the hook will not crash on the server, where document does not exist. The cleanup removes only a node carrying the data-created-by-hook attribute. A trap: Portal is a new component on every render, so React mounts its children from scratch and loses their state.
Dynamic Target
DynamicPortal accepts a selector or a ready element, and without them it picks body:
// DynamicPortal.jsx
function DynamicPortal({
children,
targetSelector,
targetElement,
fallbackToBody = true
}) {
const [target, setTarget] = useState(null);
useEffect(() => {
let targetNode = null;
if (targetElement) {
targetNode = targetElement;
} else if (targetSelector) {
targetNode = document.querySelector(targetSelector);
} else if (fallbackToBody) {
targetNode = document.body;
}
setTarget(targetNode);
}, [targetSelector, targetElement, fallbackToBody]);
if (!target) return null;
return createPortal(children, target);
}
// Usage example
function App() {
return (
<div>
<div id="sidebar-portals"></div>
<div id="header-portals"></div>
<main>
<DynamicPortal targetSelector="#sidebar-portals">
<div>Content in sidebar</div>
</DynamicPortal>
<DynamicPortal targetSelector="#header-portals">
<div>Content in header</div>
</DynamicPortal>
</main>
</div>
);
}The target is set by an effect, so on the first render target is null and nothing shows up. The content appears once querySelector finds the node.
Practical Use Cases
Modal System
Time for a real communications system. ModalProvider stores the list of open windows, and useConfirmation turns a confirmation into a promise you wait for with await:
// ModalSystem.jsx
import { createContext, useContext, useState } from 'react';
import { createPortal } from 'react-dom';
const ModalContext = createContext();
export function ModalProvider({ children }) {
const [modals, setModals] = useState([]);
const openModal = (content, options = {}) => {
const id = Date.now().toString();
const modal = {
id,
content,
...options
};
setModals(prev => [...prev, modal]);
return id;
};
const closeModal = (id) => {
setModals(prev => prev.filter(modal => modal.id !== id));
};
const closeAllModals = () => {
setModals([]);
};
return (
<ModalContext.Provider value={{ openModal, closeModal, closeAllModals }}>
{children}
{modals.length > 0 && createPortal(
<div className="modal-container">
{modals.map((modal, index) => (
<ModalOverlay
key={modal.id}
modal={modal}
zIndex={1000 + index}
onClose={() => closeModal(modal.id)}
/>
))}
</div>,
document.body
)}
</ModalContext.Provider>
);
}
function ModalOverlay({ modal, zIndex, onClose }) {
return (
<div
className="modal-overlay"
style={{ zIndex }}
onClick={modal.closeOnOverlayClick !== false ? onClose : undefined}
>
<div
className={`modal-content ${modal.className || ''}`}
onClick={e => e.stopPropagation()}
style={modal.style}
>
{modal.showCloseButton !== false && (
<button
className="modal-close"
onClick={onClose}
aria-label="Close modal"
>
ร
</button>
)}
{modal.content}
</div>
</div>
);
}
export const useModal = () => {
const context = useContext(ModalContext);
if (!context) {
throw new Error('useModal must be used within ModalProvider');
}
return context;
};
// Example components
function ConfirmationModal({ message, onConfirm, onCancel }) {
return (
<div>
<h3>Confirmation</h3>
<p>{message}</p>
<div className="modal-actions">
<button onClick={onCancel}>Cancel</button>
<button onClick={onConfirm} className="primary">
Confirm
</button>
</div>
</div>
);
}
function useConfirmation() {
const { openModal, closeModal } = useModal();
return (message) => {
return new Promise((resolve) => {
const id = openModal(
<ConfirmationModal
message={message}
onConfirm={() => {
resolve(true);
closeModal(id);
}}
onCancel={() => {
resolve(false);
closeModal(id);
}}
/>,
{ closeOnOverlayClick: false }
);
});
};
}Each subsequent modal gets a higher zIndex, so the new window lies on top. Clicking inside the content does not close the modal, because stopPropagation stops the event before it reaches the overlay.
Tooltip System
A tooltip has to stand right next to its element. TooltipProvider measures the target with getBoundingClientRect and renders the bubble in body:
// TooltipSystem.jsx
function TooltipProvider({ children }) {
const [tooltip, setTooltip] = useState(null);
const timeoutRef = useRef();
const showTooltip = (content, targetElement, options = {}) => {
clearTimeout(timeoutRef.current);
const rect = targetElement.getBoundingClientRect();
const position = calculatePosition(rect, options.position || 'top');
setTooltip({
...options,
content,
position,
placement: options.position || 'top'
});
};
const hideTooltip = (delay = 0) => {
if (delay > 0) {
timeoutRef.current = setTimeout(() => {
setTooltip(null);
}, delay);
} else {
setTooltip(null);
}
};
useEffect(() => {
return () => clearTimeout(timeoutRef.current);
}, []);
return (
<TooltipContext.Provider value={{ showTooltip, hideTooltip }}>
{children}
{tooltip && createPortal(
<div
className={`tooltip tooltip--${tooltip.placement}`}
style={{
left: tooltip.position.x,
top: tooltip.position.y,
zIndex: 9999
}}
>
{tooltip.content}
</div>,
document.body
)}
</TooltipContext.Provider>
);
}
function calculatePosition(targetRect, position) {
const tooltipSize = { width: 200, height: 40 }; // Approximate
const positions = {
top: {
x: targetRect.left + targetRect.width / 2 - tooltipSize.width / 2,
y: targetRect.top - tooltipSize.height - 8
},
bottom: {
x: targetRect.left + targetRect.width / 2 - tooltipSize.width / 2,
y: targetRect.bottom + 8
},
left: {
x: targetRect.left - tooltipSize.width - 8,
y: targetRect.top + targetRect.height / 2 - tooltipSize.height / 2
},
right: {
x: targetRect.right + 8,
y: targetRect.top + targetRect.height / 2 - tooltipSize.height / 2
}
};
return positions[position] || positions.top;
}
// Hook for easy usage
function useTooltip() {
const { showTooltip, hideTooltip } = useContext(TooltipContext);
return {
show: (content, targetRef, options) => {
if (targetRef.current) {
showTooltip(content, targetRef.current, options);
}
},
hide: hideTooltip
};
}calculatePosition computes coordinates for four sides, and the direction goes into the placement field, which produces the CSS class. The coordinates are relative to the viewport, which is why the bubble needs position: fixed.
Notification System
Notifications are a stack of messages in the corner of the screen, independent of the module that sent them. NotificationProvider adds an entry and removes it by itself after duration:
// NotificationSystem.jsx
function NotificationProvider({ children }) {
const [notifications, setNotifications] = useState([]);
const addNotification = (notification) => {
const id = Date.now().toString();
const newNotification = {
id,
type: 'info',
duration: 5000,
...notification
};
setNotifications(prev => [...prev, newNotification]);
// Auto-remove after specified time
if (newNotification.duration > 0) {
setTimeout(() => {
removeNotification(id);
}, newNotification.duration);
}
return id;
};
const removeNotification = (id) => {
setNotifications(prev => prev.filter(n => n.id !== id));
};
return (
<NotificationContext.Provider value={{ addNotification, removeNotification }}>
{children}
{createPortal(
<div className="notifications-container">
{notifications.map(notification => (
<NotificationItem
key={notification.id}
notification={notification}
onRemove={() => removeNotification(notification.id)}
/>
))}
</div>,
document.body
)}
</NotificationContext.Provider>
);
}
function NotificationItem({ notification, onRemove }) {
const [isVisible, setIsVisible] = useState(false);
const [isLeaving, setIsLeaving] = useState(false);
useEffect(() => {
// Entry animation
const timer = setTimeout(() => setIsVisible(true), 10);
return () => clearTimeout(timer);
}, []);
const handleRemove = () => {
setIsLeaving(true);
setTimeout(onRemove, 300); // Exit animation duration
};
return (
<div
className={`notification notification--${notification.type} ${
isVisible && !isLeaving ? 'notification--visible' : ''
} ${isLeaving ? 'notification--leaving' : ''}`}
>
<div className="notification-content">
{notification.title && (
<h4 className="notification-title">{notification.title}</h4>
)}
<p className="notification-message">{notification.message}</p>
</div>
{notification.actions && (
<div className="notification-actions">
{notification.actions.map((action, index) => (
<button
key={index}
onClick={() => {
action.handler();
if (action.closeOnClick !== false) {
handleRemove();
}
}}
className={`notification-action ${action.className || ''}`}
>
{action.label}
</button>
))}
</div>
)}
<button
className="notification-close"
onClick={handleRemove}
aria-label="Close notification"
>
ร
</button>
</div>
);
}
// Hook for notifications
function useNotifications() {
const { addNotification } = useContext(NotificationContext);
return {
success: (message, options) => addNotification({
type: 'success',
message,
...options
}),
error: (message, options) => addNotification({
type: 'error',
message,
duration: 0, // Don't auto-dismiss
...options
}),
warning: (message, options) => addNotification({
type: 'warning',
message,
...options
}),
info: (message, options) => addNotification({
type: 'info',
message,
...options
})
};
}Errors have duration: 0, so they do not disappear on their own. The notification--visible and notification--leaving classes drive the animation.
Event Propagation in Portals
The most important navigation lesson: where does a click inside a portal travel? The button lives in the DOM inside body, but in the React tree it is a child of the div with handleParentClick:
function PortalEventExample() {
const [count, setCount] = useState(0);
const handleParentClick = () => {
console.log('Parent clicked');
setCount(c => c + 1);
};
const handlePortalClick = (e) => {
console.log('Portal clicked');
// The event bubbles up to the parent, even though the portal sits outside it in the DOM
// e.stopPropagation(); // Stops bubbling
};
return (
<div onClick={handleParentClick} className="parent">
<p>Clicks: {count}</p>
<p>Click the button in the portal - event will bubble to parent!</p>
{createPortal(
<div className="portal-content">
<button onClick={handlePortalClick}>
Button in Portal
</button>
</div>,
document.body
)}
</div>
);
}The click calls handlePortalClick, then handleParentClick, and the counter goes up. Events from a portal flow along the React tree, not the DOM tree. If you do not want that, use e.stopPropagation().
Context Through Portals
Context works the same way: a component in a portal sees the providers of all its ancestors in the React tree:
// Context works normally through Portals
const ThemeContext = createContext();
function App() {
return (
<ThemeContext.Provider value={{ theme: 'dark' }}>
<div className="app">
<MainContent />
{/* Portal has access to ThemeContext */}
{createPortal(
<PortalComponent />,
document.getElementById('portal-root')
)}
</div>
</ThemeContext.Provider>
);
}
function PortalComponent() {
const { theme } = useContext(ThemeContext); // Works!
return (
<div className={`portal-component theme-${theme}`}>
I have access to context: {theme}
</div>
);
}PortalComponent reads the dark theme even though its HTML lives in #portal-root, outside the .app div.
Best Practices
Lifecycle
A portal that creates its own node has to clean up after itself. CleanPortal remembers whether it created the target itself, and only then removes it:
function CleanPortal({ children, targetId }) {
const [portalTarget, setPortalTarget] = useState(null);
useEffect(() => {
// Create target element if it doesn't exist
let target = document.getElementById(targetId);
let shouldCleanup = false;
if (!target) {
target = document.createElement('div');
target.id = targetId;
document.body.appendChild(target);
shouldCleanup = true;
}
setPortalTarget(target);
// Cleanup
return () => {
if (shouldCleanup && target.parentNode) {
target.parentNode.removeChild(target);
}
};
}, [targetId]);
if (!portalTarget) return null;
return createPortal(children, portalTarget);
}The shouldCleanup flag protects nodes that existed before, such as #modal-root. I recommend this pattern: one stable component and clear cleanup in the effect's cleanup function.
Accessibility
AccessibleModal moves focus into the window, locks background scrolling, closes on the Escape key and returns focus after closing, so screen readers and keyboard users do not lose the modal:
function AccessibleModal({ children, isOpen, onClose, title }) {
const modalRef = useRef();
const previousFocusRef = useRef();
useEffect(() => {
if (isOpen) {
// Save currently focused element
previousFocusRef.current = document.activeElement;
// Move focus to modal
if (modalRef.current) {
modalRef.current.focus();
}
// Lock scroll on body
document.body.style.overflow = 'hidden';
// Handle ESC key
const handleEscape = (e) => {
if (e.key === 'Escape') {
onClose();
}
};
document.addEventListener('keydown', handleEscape);
return () => {
document.removeEventListener('keydown', handleEscape);
document.body.style.overflow = '';
// Restore focus
if (previousFocusRef.current) {
previousFocusRef.current.focus();
}
};
}
}, [isOpen, onClose]);
if (!isOpen) return null;
return createPortal(
<div
className="modal-overlay"
onClick={onClose}
role="dialog"
aria-modal="true"
aria-labelledby="modal-title"
>
<div
ref={modalRef}
className="modal-content"
onClick={e => e.stopPropagation()}
tabIndex={-1}
>
<h2 id="modal-title">{title}</h2>
{children}
{/* Focus trap */}
<button
style={{ position: 'absolute', left: '-9999px' }}
onFocus={() => modalRef.current?.focus()}
/>
</div>
</div>,
document.body
);
}The role="dialog", aria-modal and aria-labelledby attributes describe the window to assistive technologies. The hidden button is a simplified focus trap, and in production consider the native <dialog> element with its showModal() method.
Performance
LazyPortal looks for its target only when isActive becomes true, and MemoizedPortal skips rendering until shouldUpdate changes:
// Lazy Portal - loads only when needed
function LazyPortal({ children, isActive, targetId }) {
const [portalRoot, setPortalRoot] = useState(null);
useEffect(() => {
if (isActive && !portalRoot) {
const root = document.getElementById(targetId) || document.body;
setPortalRoot(root);
}
}, [isActive, targetId, portalRoot]);
// Render only when active and when we have a target
if (!isActive || !portalRoot) {
return null;
}
return createPortal(children, portalRoot);
}
// Memoized Portal for frequent re-renders
const MemoizedPortal = memo(function MemoizedPortal({
children,
targetId,
shouldUpdate
}) {
const portalTarget = useMemo(() => {
return document.getElementById(targetId) || document.body;
}, [targetId]);
return createPortal(children, portalTarget);
}, (prevProps, nextProps) => {
// Custom comparison - re-render only when shouldUpdate changes
return prevProps.shouldUpdate === nextProps.shouldUpdate;
});Since the comparison looks only at shouldUpdate, new children will not appear until the flag changes.
The keys to portals are cleaning up nodes, accessibility and sensible performance. They will return in the module's main project, where a portal displays an alert when fuel drops below 20%.
Remember: a portal is a teleporter - the module appears on another deck, but its link to the mothership, meaning context and events, stays intact.
Code for this lesson: App.jsx
import { useState, useEffect, useRef, useId, useCallback, createContext, useContext } from 'react';
import { createPortal } from 'react-dom';
import './App.css';
// Ship context: the portal still sees it, even though the portal HTML goes to <body>
const ShipContext = createContext('unknown ship');
// Modal rendered through a portal straight into document.body
function AlertModal({ onClose }) {
const titleId = useId();
const dialogRef = useRef(null);
const ship = useContext(ShipContext);
// On open, focus moves into the window; on close, it returns to where it was before
useEffect(() => {
const previousFocus = document.activeElement;
dialogRef.current.querySelector('button').focus();
return () => previousFocus?.focus();
}, []);
// Escape closes the window, and Tab cycles only through the modal buttons
useEffect(() => {
function handleKeyDown(event) {
if (event.key === 'Escape') {
onClose();
return;
}
if (event.key !== 'Tab') return;
const buttons = dialogRef.current.querySelectorAll('button');
const first = buttons[0];
const last = buttons[buttons.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [onClose]);
// A click on the backdrop closes the window, and a click inside keeps travelling up the React tree
function handleBackdropClick(event) {
if (event.target === event.currentTarget) onClose();
}
return createPortal(
<div className="overlay" onClick={handleBackdropClick}>
<div
ref={dialogRef}
className="dialog"
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
>
<h2 id={titleId}>Communications module failure</h2>
<p>Ship {ship}: this message lives in the DOM directly inside body, so the overflow: hidden of the cargo hold cannot clip it.</p>
<p className="hint">Escape closes the window, Tab switches between the buttons, and focus returns to the button that opened the alarm.</p>
<div className="actions">
<button onClick={onClose}>Acknowledge</button>
<button className="secondary" onClick={onClose}>Close</button>
</div>
</div>
</div>,
document.body
);
}
// Notifications go through a portal too: a stack in the corner of the screen, outside the cargo hold
function ToastStack({ toasts, onDismiss }) {
return createPortal(
<div className="toasts" role="status" aria-live="polite">
{toasts.map((toast) => (
<Toast key={toast.id} toast={toast} onDismiss={onDismiss} />
))}
</div>,
document.body
);
}
function Toast({ toast, onDismiss }) {
// Each notification disappears after 4 seconds, and the cleanup clears the timer
useEffect(() => {
const timer = setTimeout(() => onDismiss(toast.id), 4000);
return () => clearTimeout(timer);
}, [toast.id, onDismiss]);
return (
<div className="toast">
<span>{toast.text}</span>
<button aria-label="Close notification" onClick={() => onDismiss(toast.id)}>ร</button>
</div>
);
}
export default function App() {
const [showClipped, setShowClipped] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
const [holdClicks, setHoldClicks] = useState(0);
const [toasts, setToasts] = useState([]);
const nextToastId = useRef(1);
const closeModal = useCallback(() => setModalOpen(false), []);
const dismissToast = useCallback((id) => {
setToasts((list) => list.filter((toast) => toast.id !== id));
}, []);
function sendNotification() {
const id = nextToastId.current++;
setToasts((list) => [...list, { id, text: `Report #${id}: shields operational` }]);
}
return (
<ShipContext.Provider value="Odyssey">
<main className="bridge">
<h1>React Portals - alarm on the bridge</h1>
<p className="lead">The communications module sits in a cargo hold with overflow: hidden. Compare an alarm rendered inside the hold with an alarm sent through a portal.</p>
{/* Cargo hold: overflow: hidden and its own z-index */}
<section className="cargo-hold" onClick={() => setHoldClicks((count) => count + 1)}>
<h2>Cargo hold: communications module</h2>
<p className="counter">Clicks received by the cargo hold: {holdClicks}</p>
<div className="buttons">
<button onClick={() => setShowClipped((visible) => !visible)}>
{showClipped ? 'Hide the alarm without a portal' : 'Alarm without a portal'}
</button>
<button onClick={() => setModalOpen(true)}>Alarm through a portal</button>
<button onClick={sendNotification}>Send notification</button>
</div>
{showClipped && (
<div className="clipped-alert">
<strong>Alarm without a portal</strong>
<p>This message stayed in the cargo hold, so overflow: hidden cuts off its lower part together with the emergency procedure: power down the module, switch communications to the backup antenna and report the failure to the bridge.</p>
</div>
)}
{modalOpen && <AlertModal onClose={closeModal} />}
<ToastStack toasts={toasts} onDismiss={dismissToast} />
</section>
<p className="note">The modal and the notifications land in body in the DOM, but in the React tree they are still children of the cargo hold: a click inside the open modal also raises the counter, and the modal reads the ship name from context.</p>
</main>
</ShipContext.Provider>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What are React Portals (createPortal) used for?
2. Why is it worth using createPortal to render a modal instead of rendering it directly in the component tree?
Hands-on tasks in the game
- Click in order
Arrange the createPortal syntax for rendering a modal outside the component tree: