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 PortalDemo() {
const [opened, setOpened] = useState(false);
return (
<main style={{ position: 'relative', zIndex: 1 }}>
<Portal zIndex={5}>
<div opened={opened} onClose={() => setOpened(false)}>
Your modal content
</div>
</Portal>
<button onClick={() => setOpened(true)}>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:

const container = document.createElement('div');
document.body.appendChild(container);
<Portal target={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.

Build fully functional accessible web applications with ease
Feedback
Your feedback is most valuable contribution to the project, please share how you use Mantine, what features are missing and what is done good
Leave feedback