Unlock The Power of React Portals For Seamless UI Experiences
Unlock The Power of React Portals For Seamless UI Experiences
Unlock The Power of React Portals For Seamless UI Experiences
Experiences
Create UI components that break out of their container and render anywhere in
the DOM
This can be useful when creating UI components like modals, tooltips, or dropdown menus that need to break
free from the parent’s DOM structure.
In this article, we’ll explore how to create and use React Portals with TypeScript to craft seamless UI
experiences.
interface PortalProps {
target: string;
children: React.ReactNode;
}
useEffect(() => {
const targetElement = document.getElementById(target)
const portalContainer = document.createElement('div')
if (targetElement) {
targetElement.appendChild(portalContainer)
setContainer(portalContainer)
}
return () => {
if (targetElement) {
targetElement.removeChild(portalContainer)
}
}
}, [target, setContainer])
This Portal component takes a target prop representing the DOM element's ID to render the portal's
children. It appends a new div to the target element and uses the createPortal function from React to render
the portal’s children into the newly created div.
// Modal.tsx
import React from 'react'
import Portal from './Portal'
interface ModalProps {
onClose: () => void
}
const Modal: React.FC<ModalProps> = ({ onClose, children }) => {
return (
<Portal target="modal-root">
<div className="modal-backdrop" onClick={onClose}>
<div className="modal-content" onClick={(e) => e.stopPropagation()}>
{children}
</div>
</div>
</Portal>
)
}
The Modal component takes an onClose prop to close the modal when clicking outside the modal content.
We use the Portal component to render the modal content and backdrop inside a DOM element with the
id modal-root , which we’ll define in our next file, App.tsx .
// App.tsx
import React, { useState } from 'react'
import Modal from './Modal'
return (
<div>
<button onClick={openModal}>Open Modal</button>
{isModalOpen && (
<Modal onClose={closeModal}>
<h1>Hello, I'm a modal!</h1>
<button onClick={closeModal}>Close</button>
</Modal>
)}
<div id="modal-root" />
</div>
)
}
export default App
In this demo app, we create a button that toggles the modal’s visibility. When the modal is open, we use
the <Modal> to display its content.
I put this all together as a CodeSandbox that I created with React.new. Check it out — you can click to open
and click again to close the modal.
React Portals are incredibly useful when creating components like modals, tooltips, and dropdown menus,
enabling you to craft more flexible and user-friendly interfaces. They’re also core to how Headless UI is built.
As you continue to build React apps, keep Portals in mind as a powerful tool to enhance your UI components
and create better user experiences.