Member-only story
Understanding Portals in React
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:
- The JSX/React node to render.
- 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…