dev-resources.site
for different kinds of informations.
React Portals Explained
Published at
9/28/2024
Categories
react
portals
webdev
Author
imyusufakhtar
Author
13 person written this
imyusufakhtar
open
React Portals provide a way to render children components into a DOM node that exists outside the parent component's hierarchy. This is useful when you need to render components like modals, tooltips, or dropdowns that require positioning outside of the normal flow of the component tree for better styling or functionality.
Usage of React Portals:
-
Creating a Portal:
You useReactDOM.createPortal
to create a portal. It takes two arguments:- The children (elements to render).
- The DOM node where the children should be rendered.
Basic Example:
import React from 'react';
import ReactDOM from 'react-dom';
function Modal({ children }) {
return ReactDOM.createPortal(
<div className="modal">
{children}
</div>,
document.getElementById('modal-root') // Specify the target DOM node.
);
}
function App() {
return (
<div>
<h1>Main App</h1>
<Modal>
<h2>This is a modal</h2>
</Modal>
</div>
);
}
export default App;
Explanation:
- The modal content will be rendered into the DOM node with
id="modal-root"
, which is outside the main app’s component tree.
Why use Portals?
- Modals/Overlays: Ensures they are rendered outside the DOM tree to avoid clipping and z-index issues.
- Tooltips/Dropdowns: Helps position these components more easily and avoid unwanted layout behavior.
portals Article's
9 articles in total
React Portals Explained
currently reading
Create React Portals Typed Safe
read article
React Portals: Intro
read article
Portals and giant carousels
read article
Cheese on Toast with React Portals?
read article
Your next React Modal with your own "useModal" Hook & Context API.
read article
PowerApps Portals - the GraphQL story
read article
Implemented Portals on my Portfolio site to blogs site.
read article
Exploring HTMLPortalElement with React
read article
Featured ones: