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

Dr. Derek Austin 🥳
React in the Real World
3 min readApr 17, 2023

--

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) {…

--

--

Dr. Derek Austin 🥳
React in the Real World

Hi, I'm Doctor Derek! I've been a professional web developer since 2005, and I love writing about programming with JavaScript, TypeScript, React, Next.js & Git.