Skip to content

Portal

The Portal component lets you render its children into a DOM node that exists outside of the Portal's own DOM hierarchy.

Introduction

Portal is a utility component built around React's createPortal() API. It gives you the functionality of createPortal() in a convenient component form.

The Portal component is used internally by the Modal and Popper components.

Component

Usage

After installation, you can start building with this component using the following basic elements:

<span class="token keyword">import</span> Portal <span class="token keyword">from</span> <span class="token string">'@mui/base/Portal'</span><span class="token punctuation">;</span>

<span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token keyword">function</span> <span class="token function">MyApp</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">return</span> <span class="token punctuation">(</span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span><span class="token class-name">Portal</span></span><span class="token punctuation">></span></span><span class="token punctuation">{</span><span class="token comment">/* children to be rendered outside of the current DOM node */</span><span class="token punctuation">}</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span><span class="token class-name">Portal</span></span><span class="token punctuation">></span></span>
  <span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

Basics

Normally, children of a component are rendered within that component's DOM tree. But sometimes it's necessary to mount a child at a different location in the DOM.

The Portal component accepts a container prop that passes a ref to the DOM node where its children will be mounted.

The following demo shows how a <span> nested within a Portal can be appended to a node outside of the Portal's DOM hierarchy—click Mount children to see how it behaves:

It looks like I will render here.
Press Enter to start editing

Server-side

The Portal component cannot be used to render child elements on the server—client-side hydration is necessary.