What are React Portals and when would you use them?
Portal provides a way to render children into a different part of the DOM outside of the
parent component’s DOM hierarchy. This is particularly useful for scenarios like modals,
tooltips, or popups that need to visually break out of their parent component but still maintain
their React component state.
- When to use: When you need to render content outside the DOM hierarchy of a
parent, without losing the React component context (e.g., for modals, overlays, etc.).
Example:
import React from 'react';
import ReactDOM from 'react-dom';
function Modal() {
return ReactDOM.createPortal(
<div className="modal">This is a modal</div>,
document.getElementById('modal-root') // Renders outside the
normal DOM tree
);
}
export default Modal;
In this case, the modal is rendered inside a specific part of the DOM (modal-root) even
though it is a child of the Modal component.