DEV Community

Cover image for From Root to Anywhere: How React Portals Work
Das Sameer
Das Sameer

Posted on

From Root to Anywhere: How React Portals Work

Introduction
React normally renders components into a specific DOM hierarchy. But what if you need to render something outside of that? That’s where React Portals come in.
In this post, we’ll look at what a Portal is when to use it, and how to implement one.
What Is a React Portal?
i.React Portals provide a way to render child components outside of their parent's DOM hierarchy. This functionality is useful in scenarios where a component needs to visually "break out" of its container, such as with modals, tooltips, or pop-up menus.

ii.The ReactDOM.createPortal method is used to achieve this, taking two arguments: the child element to be rendered and the DOM node where it should be rendered.

syntax-ReactDOM.createProtal(children,container)

For Example:
Let’s say we want a modal to appear above all content, even if it's deeply nested in the React tree.
HTML Structure

<body>
<div id="root"></div>
<div id="modal"></div>
</body>
Enter fullscreen mode Exit fullscreen mode

React Component

import ReactDOM from "react-dom"
import { X } from 'lucide-react';  // this is for close icon ,it is not 
                                       belongs to react portals concept

const Modal=({children})=>{    

    return ReactDOM.createPortal(
        <div className=" fixed bottom-0 top-0 overflow-hidden left-0 right-0 bg-[#00000086] flex justify-center items-center  z-50 ">
           <div className="bg-white relative   rounded-[10px] px-3 max-lg:absolute max-lg:bottom-0  min-w-[300px] lg:max-w-[600px] overflow-auto max-lg:w-full  pt-4 min-h-[300px] max-lg:h-[90vh] lg:max-h-[400px]">
                <button  className="absolute right-2 top-2 max-lg:hidden inline"><X/></button>
                {children}

           </div>
        </div>,
        document.getElementById("modal")

    )
}

export default Modal
Enter fullscreen mode Exit fullscreen mode

How to use It

<Modal> 
    <h3>This is modal Content</h3>
</Modal>
Enter fullscreen mode Exit fullscreen mode

When to use It?
React Portals used in below scenario

  • Modals and Dialogs
  • Notification Bar
  • Tooltips and dropdowns

Conclusion
This is particularly valuable for creating elements like modals, tooltips, notifications, or dropdowns that need to visually break out of their container's boundaries to avoid styling conflicts, layout issues overflow-hidden or z-index problems.

Top comments (0)