Better Programming

Advice for programmers.

Follow publication

Digging Deeper Into React Portals With Examples

Blessing Ene Anyebe
Better Programming
Published in
6 min readJan 17, 2023
Photo by Misael Moreno on Unsplash
Table of Contents

Introduction

What Is React Portal

How To Use/Create React Portals

Examples With React Portals

Wrapping Up

Further References

React Portals is a feature in the React JavaScript library that provides a way to render a React component at a different location in the DOM instead of where it is declared. According to the React documentation, React Portals offer a method to render children into a DOM node that is not part of the parent component’s DOM hierarchy.

React Portals are like the secret passageway you can use to escape a crazy castle cramped with people.

You can see React Portals as a teleportation device for your React components. They allow you to send a component to a different place in the DOM, even if it is outside the parent component’s DOM tree. It’s like saying, “Hey, this component is feeling a little cramped in its current location. Can it go hang out over there for a while?”

React Portals are a way to render a piece of React content outside of the current component tree. It is useful when you want to have a parent-child relationship in your components while you want to render a child component outside of the parent.

How To Use/Create React Portals

To use React Portals, you will need to create a container element in the normal HTML DOM you will use as the target for your React content. It can be any valid HTML element or renderable React children, such as a div, span, section, string, or fragment.

Portal container element created in HTML DOM.

Here, we’ve created our portal home (container element) outside our regular “root” element.

Once you have created the container element, you can use the ReactDOM.createPortal() method to render a React element. The createPortal() function takes two arguments: the React element to render and the container element. Here is an example:

ReactDOM.createPortal(<childElement />, container);

After calling createPortal(), the React element you provided will be rendered into the container element and treated like any other React element in your application. You can update it, pass props to it, add event listeners, and so on. You’ll see more in the examples. When the element is unmounted, the portal and its content get automatically removed from the DOM.

React Portal is helpful as it can help with performance by allowing you to render some components outside of the main React component hierarchy. Having fewer components that need rerendering each time your application’s state changes can boost your application’s overall performance.

What Are All the Things React Portals Can Do?

React Portals can increase your application’s flexibility and maintainability by allowing you to manage different parts of your user interface in a better modular way. Some other roles it plays include the following:

  • Rendering components with complex rendering behavior, such as modals, popovers, and tooltips.
  • It creates a separate root for some components, allowing them to be managed independently from the rest of the application.
  • It creates components that appear on top of other elements on the page without conflicts with other elements in the component tree.
  • It improves the performance of an application by rendering some components outside of the main React component hierarchy.

Building Stuff With React Portals

Example 1: DropDown

//APP.JS

import React, { useState } from 'react';
import { createPortal } from 'react-dom';

import './Dropdown.css';

const Dropdown = () => {
const [isOpen, setIsOpen] = useState(false);

const toggleDropdown = () => {
setIsOpen(!isOpen);
}

return (
<div className="dropdown">
<button className='Dropdown-btn' onClick={toggleDropdown}>
Dropdown
</button>
{isOpen && createPortal(
<div className="dropdown-menu">
<ul>
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>
</div>,
document.getElementById("portal")
)}
</div>
);
};

export default Dropdown;

In this code, we have a React component called Dropdown that renders a Dropdown menu when clicking the button. Utilizing React Portal, we render the Dropdown menu outside of the Dropdown component’s DOM hierarchy. The Dropdown component has a state variable called isOpen that determines whether the dropdown menu is open or closed.

When the button gets clicked, the toggleDropdown function gets called, which toggles the value of isOpen — the Options. If isOpen is true, the dropdown menu gets rendered using the createPortal function from React DOM. When the dropdown menu is closed, the createPortal function does not render anything, so the Dropdown menu is not displayed. When the button gets clicked again, toggleDropdown gets called, which sets isOpen to false and closes the dropdown menu.

You can play with the output here:

Example 2: Tooltip

import React, { useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';

const Tooltip = ({ text, children }) => {
const [showTooltip, setShowTooltip] = useState(false);
const ref = useRef();

useEffect(() => {
const onMouseEnter = () => setShowTooltip(true);
const onMouseLeave = () => setShowTooltip(false);
ref.current.addEventListener('mouseenter', onMouseEnter);
ref.current.addEventListener('mouseleave', onMouseLeave);

return () => {
ref.current.removeEventListener('mouseenter', onMouseEnter);
ref.current.removeEventListener('mouseleave', onMouseLeave);
};
}, []);

const tooltip = showTooltip ? (
<div className="tooltip">{text}</div>
) : null;

return (
<div ref={ref}>
{children}
{createPortal(tooltip, document.body)}
</div>
);
};

const App = () => (
<div className="container">
<Tooltip text="This is a tooltip">
<button className="btn">Hover me</button>
</Tooltip>
</div>
);

export default App;

In this example, we displayed the tooltip text when the mouse hovers over the button and close it when it leaves. However, using the React Portal, which allows us to place the tooltip text outside of the DOM hierarchy, we can use the tooltip in our component without affecting the layout so that the tooltip may get positioned absolutely.

You can play with the output here:

Example 3: Modal dialog box

import React, { useState, useRef } from 'react';
import { createPortal } from 'react-dom';
import "./Modal.css"
const Modal = ({ children, onClose }) => {
const [isOpen, setIsOpen] = useState(true);
const modalRef = useRef();
const closeModal = e => {
if (e.target === modalRef.current) {
setIsOpen(false);
onClose();
}
};
if (!isOpen) {
return null;
}
return createPortal(
<div className="modal-overlay" ref={modalRef} onClick={closeModal}>
<div className="modal-content">
<button className="modal-close" onClick={closeModal}>
×
</button>
{children}
</div>
</div>,
document.body
);
};
const App = () => {
const [isModalOpen, setIsModalOpen] = useState(true);
const openModal = () => setIsModalOpen(true);
const closeModal = () => setIsModalOpen(false);
return (
<div className="container">
<button onClick={openModal}>Open modal</button>
{isModalOpen && (
<Modal onClose={closeModal}>
<h1>Modal title</h1>
<p>Modal content</p>
</Modal>
)}
</div>
);
};
export default App;

It will display the modal when the “Open modal” button gets clicked and close it when the “×” button or the overlay gets clicked. The modal gets rendered using React Portal, which allows it to be placed outside the DOM hierarchy of the React component. It can be helpful if you want to put the modal exactly where you want it to be or when you don’t want it to interfere with how the component gets laid out.

You can play with the output here:

Wrapping Up

We have covered practical examples of React Portals in action to iterate; React portals are a way to render a React component tree to a different DOM element than the parent component. Here are a few things to note while working with React Portals:

  • Portals provide a way to escape the DOM hierarchy while rendering a React component. You can use portals to render children into a DOM element outside the parent component.
  • To create a portal, you will need to use the ReactDOM.createPortal function and pass it two arguments: the JSX element you want to render and the DOM element where you want to render it.
  • Portals are a good solution for cases where you want to render a child component outside the parent component’s DOM tree, such as when you want to render a modal or tooltip.
  • Remember to clean up any event listeners or timers when you unmount a component that uses portals, as the portal and the parent component are not in the same React tree.
  • The location of the content is only different on the DOM, but it still follows the React component hierarchy. This is why props and event listeners can be passed to such children components.

I like React Portals and recommend it as an optimization technique you could use in your code.

Thank you for reading!

Further Reference

React Portal Simplified — Dillion Megida

Learn React Portals by Examples

Want to Connect?

Connect with me on LinkedIn and Twitter.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Blessing Ene Anyebe
Blessing Ene Anyebe

Written by Blessing Ene Anyebe

Laying hold of my life’s journey through Writing, and Frontend development. I found my voice in Christ. I cherish every win against ignorance.

Write a response