Member-only story

Understanding Portals in React

CodeByUmar
3 min readDec 12, 2024

What Are Portals in React?

Portals in React provide a way to render components outside their parent DOM hierarchy. While React maintains the internal component hierarchy, the resulting DOM elements can be inserted elsewhere in the DOM tree. This is particularly useful for UI elements like modals, tooltips, or dropdowns, where you want the element to render at a global level rather than being confined within its parent container.

React introduced portals in version 16.

How Do Portals Work?

Portals are created using the ReactDOM.createPortal method. This method takes two arguments:

  1. The JSX/React node to render.
  2. The target DOM element where the node should be rendered.

Basic Syntax

ReactDOM.createPortal(children, container);
  • children: The React component or JSX to render.
  • container: The DOM element where the content should be rendered.

Example: Creating a Modal Using Portals

Step 1: Define the Modal Component

Here’s a simple modal component using a portal.

import React from…

--

--

CodeByUmar
CodeByUmar

Written by CodeByUmar

Full Stack Developer sharing insights on JavaScript, React, and web development. Passionate coder and problem solver exploring new tech. 🚀

No responses yet