Web Application Development
Software Development

Mastering React Portals: A Deep Dive into Advanced Rendering

Blog bannerBlog banner

Introduction of React Portals

React has revolutionised the way developers build web applications by offering an efficient, component-based architecture. One of its powerful but often overlooked features is React Portals. This feature enables developers to render components outside their usual parent hierarchy while maintaining a seamless user experience.

In this blog, we’ll explore the advantages, use cases, and implementation of React Portals, along with best practices for integrating them into your projects.

What Are React Portals?

React Portals allow developers to render a component outside the traditional DOM hierarchy of its parent component. This means that while a component is logically part of the React tree, it can be rendered in a different location in the DOM tree.

How Do React Portals Work?

By default, React components render within their parent hierarchy. However, with portals, a component can be rendered elsewhere in the DOM while still behaving as if it were inside the parent. This is particularly useful for cases like modals, tooltips, and dropdowns where DOM hierarchy restrictions might create issues.

Basic example of React Portals

Code

    import React from "react";
    import ReactDOM from "react-dom";
    
    const modalRoot = document.getElementById("modal-root");
    
    const Modal = ({ children }) => {
        return ReactDOM.createPortal(
        <div className="modal">{children}</div>,
        modalRoot
        );
    };
    
    export default Modal;
            

In this example, the modal is logically part of the React component tree but is rendered inside the modal-root div instead of the usual parent hierarchy.

Advantages of Using React Portals

1. Avoiding Parent Overflow Issues

One of the primary use cases for portals is rendering elements that need to break out of their parent container’s overflow restrictions. For example, if a modal or dropdown is inside a parent with overflow: hidden, using portals ensures that the element renders properly outside this constraint.

2. Improved Accessibility and Focus Management

When dealing with modals or popups, keeping them outside the normal DOM hierarchy allows better management of focus and accessibility attributes. This improves user experience, particularly for screen readers and keyboard navigation.

3. Simplifies Event Handling

Since portals render elements outside their original parent, event bubbling works differently. This can be useful when dealing with event listeners, preventing unintended side effects due to parent container restrictions.

Hire Now!

Hire React.js Developers Today!

Ready to bring your web application vision to life? Start your journey with Zignuts expert React.js developers.

**Hire now**Hire Now**Hire Now**Hire now**Hire now

Common Use Cases of React Portals

1. Modals and Dialogs

Modals need to overlay the entire page, making portals an ideal solution. By rendering modals at the root level, they bypass layout constraints of their parent components.

jsx

Code

    const Modal = ({ isOpen, children }) => {
        if (!isOpen) return null;
        return ReactDOM.createPortal(
            <div className="modal-overlay">
            <div className="modal-content">{children}</div>
            </div>,
            document.getElementById("modal-root")
        );
    };                  
            

2. Tooltips

Tooltips often require positioning that might not work well within deeply nested components. Using portals helps maintain their position outside parent boundaries.

jsx

Code

    const Tooltip = ({ text, targetRef }) => {
        const tooltipRoot = document.getElementById("tooltip-root");
        const { top, left, width } = targetRef.current.getBoundingClientRect();
        
        return ReactDOM.createPortal(
            <div className="tooltip" style={{ top: top + 10, left: left + width / 2 }}>
            {text}
            </div>,
            tooltipRoot
        );
    };                  
            

3. Dropdown Menus

Dropdowns often need to break out of their parent containers, particularly if nested inside flex or grid structures. Portals allow correct positioning.

jsx

Code

    const Dropdown = ({ isOpen, children }) => {
        if (!isOpen) return null;
        return ReactDOM.createPortal(
            <div className="dropdown-menu">{children}</div>,
            document.getElementById("dropdown-root")
        );
    };      
            

Best Practices for Using React Portals

1. Use Unique Root Elements

Each portal should have a dedicated root element in the HTML to avoid conflicts. Typically, portals are defined inside index.html like this:

html

Code

    <div id="modal-root"></div>
    <div id="tooltip-root"></div>
    <div id="dropdown-root"></div>                     
            

2. Manage Focus Properly

When opening a modal or dropdown, the focus shifts to the new element. Also, handle closing behaviour with the Escape key.

jsx

Code

    useEffect(() => {
        const handleKeyDown = (event) => {
            if (event.key === "Escape") {
            closeModal();
            }
        }
        document.addEventListener("keydown", handleKeyDown);
        return () => document.removeEventListener("keydown", handleKeyDown);
    }, []);                
            

3. Handle Event Bubbling

Events inside portals don’t bubble up to the parent component by default. To ensure proper event handling, explicitly manage event propagation.

Code

    const stopPropagation = (e) => e.stopPropagation();

    return ReactDOM.createPortal(
        <div className="modal-overlay" onClick={closeModal}>
        <div className="modal-content" onClick={stopPropagation}>
            {children}
        </div>
        </div>,
        modalRoot
    );                              
            

Conclusion

React Portals provide a seamless way to render components outside their traditional hierarchy while maintaining their logical position in the React tree. Whether you’re building modals, tooltips, or dropdowns, portals ensure that your UI remains functional and visually correct.

By following best practices like event handling and accessibility considerations, you can leverage portals effectively in your projects.

💡 Are you using React Portals in your applications? Let’s discuss your experience.

card user img
Twitter iconLinked icon

A problem solver with a passion for building robust, scalable web solutions that push the boundaries of technology and deliver impactful results

Let’s Connect

Exclusive Free Consultation

Valid number
Claim My Spot!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
download ready
Thank You
Your submission has been received.
We will be in touch and contact you soon!

Our Latest Blogs

Load More

Our Latest Blogs

View All Blogs