Two small, specific tools that solve two unrelated problems: satisfying JSX's one-root-element rule without adding clutter to the page, and rendering something outside where it's written in the component tree.
The JSX Syntax lesson showed that a component can only return one root element — the usual fix is wrapping everything in a <div>. But that extra <div> becomes a real element in the actual page, which can break CSS that expects specific parent-child relationships (a CSS grid, for instance, where every direct child matters):
function TableRow() {
return (
<tr>
{/* An extra <div> here would be invalid HTML inside a <tr> */}
</tr>
);
}A Fragment groups elements the same way a <div> would, but leaves no trace in the actual DOM:
import { Fragment } from 'react';
function ItemDetails() {
return (
<Fragment>
<dt>Name</dt>
<dd>Priya</dd>
</Fragment>
);
}
// The shorthand — used almost everywhere in real code:
function ItemDetails() {
return (
<>
<dt>Name</dt>
<dd>Priya</dd>
</>
);
}Shorthand has one limitation
The <>...</> shorthand can't take a key prop — inside a .map() that needs one (from the Rendering Lists and Keys lesson), use the full <Fragment key={...}> form instead.
A portal renders a component's output into a different DOM node entirely, while it stays in its normal place in the React component tree for everything else (props, context, event bubbling). This solves a real CSS problem: a modal or tooltip nested deep inside a component with overflow: hidden or a constrained z-index can visually escape that container by rendering directly into document.body instead:
import { createPortal } from 'react-dom';
function Modal({ children }) {
return createPortal(
<div className="modal-overlay">{children}</div>,
document.body
);
}Modal can still be written and used exactly like any other component — <Modal>...</Modal> — nothing about how it's called changes; only where its markup physically ends up in the DOM does.