React Portals: Expand Your Toolbox Beyond Prop Drilling

Trending 3 weeks ago

React components promote bully practices but they tin beryllium excessively restrictive. Learn really to break nan mould.

A portal illustration utilized to signify nan quality of respond portals

Key Takeaways

  • React Portals let you to render a component's contented extracurricular of its genitor constituent hierarchy, making it useful for UI elements for illustration modals and overlays.
  • Portals tin beryllium utilized successful various scenarios specified arsenic modals, third-party integrations, discourse menus, and tooltips, allowing for elastic rendering astatine different DOM locations.
  • By utilizing React Portals, you tin abstracted UI concerns from nan main constituent tree, heighten codification maintainability, and easy power nan z-index of components for layering and stacking UI elements.

Modern web applications request interfaces that characteristic elements for illustration modals and tooltips. But these UI components mightiness not ever merge good pinch nan existing constituent structure.

React offers a solution to this problem done a characteristic called Portals.

What Are React Portals?

React Portals supply a measurement to render a component's contented extracurricular its genitor constituent hierarchy. In different words, they let you to render a component's output into a different DOM constituent that is not a kid of nan existent component.

This characteristic is useful erstwhile dealing pinch UI components that request to render astatine a higher level successful nan DOM, specified arsenic modals aliases overlays.

How respond portals and render UI elements extracurricular nan element's hierarchy

Uses for React Portals

React Portals travel successful useful successful various scenarios:

  • Modals and overlays. When you request to show modal dialogues aliases overlays, render them astatine nan apical level of nan DOM. This ensures that their parent's styles aliases layout don't limit them.
  • Third-party integrations. When integrating third-party libraries that expect rendering astatine circumstantial DOM locations.
  • Context menus. Creating discourse menus that respond to personification interactions, that you request to position comparative to nan viewport aliases a circumstantial DOM element.
  • Tooltips and popovers. When rendering tooltips aliases popovers that must look connected apical of different components, sloppy of their position successful nan constituent tree.

How React Portals Work

Traditionally, erstwhile you render a constituent successful React, you connect its output to nan genitor component's DOM node. This useful good for astir scenarios, but it becomes limiting erstwhile you request to render contented extracurricular nan parent's hierarchy.

Suppose you're creating a modal dialogue. By default, you'll spot nan modal's contented wrong nan parent component's DOM node.

This tin lead to styling conflicts, and different unintended behaviour since nan modal's contented inherits nan styles and constraints of its genitor components.

React Portals reside this limitation by letting you specify a target DOM constituent wherever a component's output should render.

This intends you tin render immoderate UI constituent extracurricular nan parent's DOM hierarchy, breaking free from nan constraints of nan parent's styles and layout.

How to Use React Portals

Modals are a cleanable illustration of erstwhile you mightiness usage React Portals. This sample codification explains nan procedure.

Set Up a Basic React Application

Before creating a portal, make judge you person a basal React exertion group up. You tin usage tools for illustration Create React App to quickly scaffold a project.

React app files building aft initialization

Create a Portal for Modals

To create a portal, usage nan ReactDOM.createPortal() function. It takes 2 arguments: nan contented you want to render, and a reference to nan DOM node to render it in.

In this example, nan Modal constituent renders its children utilizing a portal. The contented will look successful nan DOM constituent pinch nan ID ‘root’.

import ReactDOM from "react-dom";

const Modal = ({ children }) => {
  const modalRoot = document.getElementById("root");
  return ReactDOM.createPortal(children, modalRoot);

export default Modal;

You tin specify nan contents of a circumstantial Modal successful a circumstantial component. For example, this ModalContent constituent contains a paragraph and a Close button:

const ModalContent = ({ onClose }) => (
  <div className="modal">
    <div className="modal-content">
      <p>This is simply a modal content.</p>
      <button onClick={onClose}>Close</button>

export default ModalContent;

You tin past unfastened nan Modal via a fastener click defined successful App.js:

import { useState } from "react";
import Modal from "./Modal";
import ModalContent from "./ModalContent";
import "./App.css";

const App = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const toggleModal = () => {

  return (
      <button onClick={toggleModal}>Open Modal</button>
      {isModalOpen && (
          <ModalContent onClose={toggleModal} />

export default App;

In this example, nan Modal constituent renders its contented utilizing a portal, detached from nan main constituent hierarchy.

Real-World Examples

React Portals are useful successful various mundane situations.

  • Notification system: When creating a notification system, you often want messages astatine nan screen's top, nary matter wherever nan existent constituent is.
  • Context menu: Context menus should popular up adjacent to wherever nan personification clicks, sloppy of wherever that is successful nan DOM hierarchy.
  • Third-party integration: Third-party libraries often request to target arbitrary parts of nan DOM.

Best Practices for Portal Use

To get nan astir retired of React Portals, travel these tips:

  • Select nan correct cases: Portals are flexible, but not everything needs them. Use portals erstwhile regular rendering causes problems aliases clashes.
  • Keep portal contented separate: When you render contented done portals, make judge it's self-contained. It shouldn't trust connected genitor styles aliases context.
  • Manage events and actions: With portals, events activity a spot otherwise because of nan detached content. Handle arena propagation and actions properly.

Benefits of React Portals

React Portals connection respective benefits that tin heighten nan improvement of analyzable personification interfaces. They:

  • Help abstracted UI concerns from nan main constituent tree, improving codification maintainability and readability.
  • Provide elasticity for components that request to show extracurricular their genitor component.
  • Make it easy to create modals and overlays that are abstracted from nan remainder of nan UI.
  • Let you easy power nan z-index of components, ensuring you tin neatly furniture and stack your UI elements.

Potential Pitfalls and Considerations

While React Portals are helpful, support these things successful mind:

  • CSS issues: Portals tin origin unexpected CSS style behaviour since they put contented extracurricular genitor components. Use world styles aliases negociate CSS scope carefully.
  • Accessibility: When you usage portals to render content, retrieve to support accessibility features for illustration keyboard navigation and surface scholar compatibility intact.
  • Server-side rendering: Portals mightiness not mesh good pinch server-side rendering (SSR). Understand nan effects and limitations of utilizing portals successful SSR setups.

Propelling UI Beyond nan Norm

React Portals connection a beardown solution for handling intricate UI situations that request contented to look beyond nan limits of genitor components.

By grasping portals and utilizing champion practices, you tin build personification interfaces that are much adaptable and easier to maintain, each while avoiding issues.

Whether you're crafting modals aliases bringing successful third-party libraries, React Portals supply a powerful reply for addressing demanding UI needs.

Source Tutorials