Fragments and Portals
7 min read
Fragments
Fragments (<>…</> or <React.Fragment>) let you group multiple elements without adding an extra DOM node. This is important when rendering table rows, list items, or elements that must be direct children of a specific parent.
jsx
function TableRow({ name, score }) {
return (
// Without Fragment, we'd need a wrapping <div> which breaks <table> structure
<>
<td>{name}</td>
<td>{score}</td>
</>
);
}Portals
ReactDOM.createPortal(children, domNode) renders children into a different DOM node than their React parent — typically document.body. This is the standard technique for modals, tooltips, and dropdowns that need to escape overflow:hidden or z-index constraints.
jsx
import { createPortal } from 'react-dom';
function Modal({ children, onClose }) {
return createPortal(
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content" onClick={e => e.stopPropagation()}>
{children}
</div>
</div>,
document.body
);
}Ready to test yourself?
Practice React— quiz & coding exercises