Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

React Portals

1. Introduction

React Portals provide a way to render children into a DOM node that exists outside of the parent component’s hierarchy. This is particularly useful for modals, tooltips, and other UI elements that need to visually break out of their container.

2. Key Concepts

What is a Portal?

A portal is a first-class way to render children into a DOM node that is outside the parent component's DOM hierarchy. The child components can be rendered anywhere in the DOM tree.

Key Characteristics

  • Portals allow for rendering components outside the parent hierarchy.
  • They maintain the React component lifecycle.
  • Portals can be useful for managing overlays, modals, and tooltips.

3. Creating Portals

To create a portal, you can use the ReactDOM.createPortal method. Below is a step-by-step guide:

Step-by-Step Process

  1. Import React and ReactDOM.
  2. Create a new component that will use the portal.
  3. Use ReactDOM.createPortal to render the component into a different DOM node.

Example Code

import React from 'react';
import ReactDOM from 'react-dom';

const Modal = ({ children, isOpen, onClose }) => {
    if (!isOpen) return null;

    return ReactDOM.createPortal(
        
{children}
, document.getElementById('modal-root') // This is the target DOM node ); }; export default Modal;

4. Best Practices

Always ensure that the target DOM node for the portal is available in the HTML file.
  • Use portals for components that need to visually escape their parent.
  • Ensure accessibility by managing focus and keyboard navigation.
  • Cleanup on unmount to avoid memory leaks.

5. FAQ

What is the difference between a portal and a traditional component?

Portals allow rendering outside the parent component's DOM hierarchy, while traditional components render within their parent.

Can I use portals with functional components?

Yes, portals work seamlessly with both class and functional components.

Are portals accessible?

Portals can be made accessible by managing focus and ensuring keyboard navigation is effective.