Middle
Tell me about fragments and portals in React.
sobes.tech AI
Answer from AI
Fragments in React are a way to group multiple elements without adding an extra DOM node. This is useful when you want to return multiple sibling elements from a component but don't want to create an additional <div>.
Example of usage:
return (
<>
<h1>Title</h1>
<p>Paragraph of text</p>
</>
);
Portals allow rendering child elements of a component into a DOM node that exists outside the hierarchy of the parent component. This is convenient for modal windows, tooltips, and other elements that should visually escape the current container.
Example of creating a portal:
import ReactDOM from 'react-dom';
function Modal({ children }) {
return ReactDOM.createPortal(
<div className="modal">
{children}
</div>,
document.getElementById('modal-root')
);
}
Thus, fragments help avoid unnecessary wrappers in the DOM, and portals render components outside the current DOM hierarchy.