Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

React - Portals

Using React portals for rendering children into different parts of the DOM

React portals provide a way to render children into a DOM node that exists outside the hierarchy of the parent component. This tutorial covers how to create and use React portals for rendering children into different parts of the DOM.

Key Points:

  • Portals provide a first-class way to render children into a DOM node outside the parent component hierarchy.
  • They are useful for rendering modals, tooltips, and other elements that need to break out of the parent container's overflow or z-index constraints.
  • Portals maintain the React tree structure and event bubbling.

Creating a Portal

To create a portal, you use the ReactDOM.createPortal method, which takes two arguments: the children to render and the DOM node to render them into.


// src/PortalExample.js
import React from 'react';
import ReactDOM from 'react-dom';

const portalRoot = document.getElementById('portal-root');

class PortalExample extends React.Component {
    render() {
        return ReactDOM.createPortal(
            this.props.children,
            portalRoot
        );
    }
}

export default PortalExample;
                

Using the Portal Component

To use the portal component, you simply render it with the children you want to render into the portal.


// src/App.js
import React from 'react';
import PortalExample from './PortalExample';

function App() {
    return (
        <div>
            <h1>React Portal Example</h1>
            <PortalExample>
                <div style={{ background: 'lightblue', padding: '20px', position: 'fixed', top: '50px', right: '50px' }}>
                    This is rendered using a portal!
                </div>
            </PortalExample>
        </div>
    );
}

export default App;
                

Example: Modal with Portal

Here is an example of using a portal to render a modal dialog.


// src/Modal.js
import React from 'react';
import ReactDOM from 'react-dom';

const modalRoot = document.getElementById('modal-root');

class Modal extends React.Component {
    render() {
        return ReactDOM.createPortal(
            <div style={{ background: 'white', padding: '20px', border: '1px solid black', boxShadow: '0 0 10px rgba(0, 0, 0, 0.5)', position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }}>
                {this.props.children}
            </div>,
            modalRoot
        );
    }
}

export default Modal;

// src/App.js
import React, { useState } from 'react';
import Modal from './Modal';

function App() {
    const [isOpen, setIsOpen] = useState(false);

    return (
        <div>
            <h1>React Modal Example</h1>
            <button onClick={() => setIsOpen(true)}>Open Modal</button>
            {isOpen && (
                <Modal>
                    <h2>This is a modal</h2>
                    <button onClick={() => setIsOpen(false)}>Close Modal</button>
                </Modal>
            )}
        </div>
    );
}

export default App;
                

Best Practices

Here are some best practices for using portals in your React applications:

  • Use portals for rendering components that need to break out of the parent container's overflow or z-index constraints, such as modals, tooltips, and dropdowns.
  • Ensure that the DOM node you render into is part of the document and correctly positioned in the DOM tree.
  • Maintain accessibility by managing focus and providing appropriate ARIA attributes.
  • Use portals sparingly and only when necessary, as overusing them can make your application harder to understand and maintain.

Summary

In this tutorial, you learned about using React portals to render children into different parts of the DOM. Portals provide a first-class way to render children outside the parent component hierarchy, which is useful for rendering modals, tooltips, and other elements that need to break out of the parent container's constraints. By creating and using portals, and following best practices, you can enhance the flexibility and usability of your React applications.