Unlock The Power of React Portals For Seamless UI Experiences

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Unlock the Power of React Portals for Seamless UI

Experiences
Create UI components that break out of their container and render anywhere in
the DOM

Photo by Vaibhav Raina on Unsplash

Introduction: The Power of React Portals 🌌


React Portals provide a powerful way to render child components into a DOM node outside of their parent
component.

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.

#1. Create a Simple Portal


First, let’s create a simple Portal component:
// Portal.tsx
import React, { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'

interface PortalProps {
target: string;
children: React.ReactNode;
}

const Portal: React.FC<PortalProps> = ({ target, children }) => {


const [container, setContainer] = useState<HTMLElement | null>(null)

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])

return container ? createPortal(children, container) : null


}

export default Portal

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.

#2. Use the Portal Component


Now, let’s use our Portal component to create a modal:

// 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>
)
}

export default Modal

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 .

#3. Create a Demo Application with React Portal


Finally, let’s create a demo application to showcase our Modal component:

// App.tsx
import React, { useState } from 'react'
import Modal from './Modal'

const App: React.FC = () => {


const [isModalOpen, setIsModalOpen] = useState(false)

const openModal = () => {


setIsModalOpen(true)
}

const closeModal = () => {


setIsModalOpen(false)
}

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.

Conclusion: The Power of React Portals 🌌


In this article, we’ve explored how to harness the power of React Portals with TypeScript to create seamless UI
experiences. By using portals, we can break free from the constraints of the parent component’s DOM
structure and render components anywhere in the DOM. (Take that, DOM tree!)

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.

You might also like