Portal

Render component outside of current context
Import

Usage

Portal is wrapper component for ReactDOM.createPortal API. Render any component or element at the end of document.body or at given element. Modal and Drawer components are wrapped in Portal by default.

Use Portal to render component or element at different place (defaults to the end of document.body). Portal is useful when you want to prevent parent styles from interfering with child, usually all these styles are related to position and z-index properties and portals are used for components with fixed position, for example, modals.

import { useState } from 'react';
import { Portal } from '@mantine/core';
function Demo() {
const [opened, setOpened] = useState(false);
return (
<main style={{ position: 'relative', zIndex: 1 }}>
{opened && (
<Portal>
<div>Your modal content</div>
</Portal>
)}
<button onClick={() => setOpened(true)} type="button">
Open modal
</button>
</main>
);
}

In the example above, div element is rendered outside of parent main (before closing body tag), but still receives opened and onClose props. Element will not be affected by parent z-index.

Specify target dom node

You can specify dom node where portal will be rendered by passing target prop:

import { Portal } from '@mantine/core';
const container = document.createElement('div');
document.body.appendChild(container);
function Demo() {
return <Portal target={container}>My portal</Portal>;
}

Alternatively, you can specify selector to render portal in existing element:

<Portal target="#my-portal-container" />

If you don't specify the target element, new one will be created and appended to the document.body for each Portal component.

Server side rendering

createPortal is not supported during server side rendering. All components inside Portal are rendered only after application was mounted to the dom.

OptionalPortal component

OptionalPortal component lets you configure whether children should be rendered in Portal. It accepts the same props as Portal component:

import { OptionalPortal } from '@mantine/core';
function Demo() {
return (
<>
<OptionalPortal withinPortal>This text is rendered in Portal</OptionalPortal>
<OptionalPortal withinPortal={false}>This text is rendered as regular child</OptionalPortal>
</>
);
}

Portal component props

NameTypeDescription
children *
ReactNode
Portal children, for example, modal or popover
innerRef
MutableRefObject<HTMLDivElement>
Root element ref
target
string | HTMLElement
Element where portal should be rendered, by default new div element is created and appended to document.body