Modal

An accessible overlay dialog

Usage

import { useDisclosure } from '@mantine/hooks';
import { Modal, Button } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  return (
    <>
      <Modal opened={opened} onClose={close} title="Authentication">
        {/* Modal content */}
      </Modal>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

useModal hook

useModal hook opens a modal from any component without rendering Modal in JSX. It accepts Modal props and returns an object with open, close, toggle and isOpened functions. The modal is rendered by MantineProvider, and all props, including children, are updated every time the component that called the hook renders:

import { useState } from 'react';
import { Button, Group, Text, useModal } from '@mantine/core';

function Demo() {
  const [count, setCount] = useState(0);
  const modal = useModal({
    title: `Count: ${count}`,
    children: (
      <>
        <Text mb="md">The modal is updated every time the parent component renders: {count}</Text>
        <Button fullWidth onClick={() => setCount((c) => c + 1)}>
          Increment
        </Button>
      </>
    ),
  });

  return (
    <Group justify="center">
      <Button onClick={() => modal.open()}>Open modal</Button>
      <Button variant="default" onClick={() => setCount((c) => c + 1)}>
        Increment ({count})
      </Button>
    </Group>
  );
}

modal.open accepts props that are applied on top of the hook options until the next modal.open call. Use it to open the same modal with different content. The content is remounted on every modal.open call unless keepMounted is set, so a form inside it always starts from its initial values:

import { Button, Group, Text, useModal } from '@mantine/core';

const users = ['Ann Smith', 'John Doe', 'Mary Bright'];

function Demo() {
  const modal = useModal({ title: 'Delete user', size: 'sm' });

  return (
    <Group justify="center">
      {users.map((user) => (
        <Button
          key={user}
          variant="default"
          onClick={() =>
            modal.open({
              children: (
                <>
                  <Text mb="md">Are you sure you want to delete {user}?</Text>
                  <Button color="red" fullWidth onClick={() => modal.close()}>
                    Delete {user}
                  </Button>
                </>
              ),
            })
          }
        >
          Delete {user}
        </Button>
      ))}
    </Group>
  );
}

useModal can be called in list items, for example, to render a delete confirmation for each table row:

NameEmail
Ann Smithann@mantine.dev
John Doejohn@mantine.dev
Mary Brightmary@mantine.dev
import { Button, Table, Text, useModal } from '@mantine/core';

const users = [
  { id: 1, name: 'Ann Smith', email: 'ann@mantine.dev' },
  { id: 2, name: 'John Doe', email: 'john@mantine.dev' },
  { id: 3, name: 'Mary Bright', email: 'mary@mantine.dev' },
];

function UserRow({ user }: { user: (typeof users)[number] }) {
  const modal = useModal({
    title: `Delete ${user.name}`,
    children: (
      <>
        <Text mb="md">Are you sure you want to delete {user.name}?</Text>
        <Button color="red" fullWidth onClick={() => modal.close()}>
          Delete
        </Button>
      </>
    ),
  });

  return (
    <Table.Tr>
      <Table.Td>{user.name}</Table.Td>
      <Table.Td>{user.email}</Table.Td>
      <Table.Td>
        <Button size="compact-xs" color="red" variant="light" onClick={() => modal.open()}>
          Delete
        </Button>
      </Table.Td>
    </Table.Tr>
  );
}

function Demo() {
  return (
    <Table>
      <Table.Thead>
        <Table.Tr>
          <Table.Th>Name</Table.Th>
          <Table.Th>Email</Table.Th>
          <Table.Th />
        </Table.Tr>
      </Table.Thead>
      <Table.Tbody>
        {users.map((user) => (
          <UserRow key={user.id} user={user} />
        ))}
      </Table.Tbody>
    </Table>
  );
}

useModal accepts the following options in addition to Modal props:

  • id – modal id, used as id and stackId of the rendered Modal, generated automatically if not set
  • defaultOpened – initial opened state, false by default
  • onOpen – called when the modal is opened
  • onClose – called when the modal is closed with modal.close(), close button, overlay click or Escape key

Modals opened with useModal and drawers opened with useDrawer are rendered in one stack, a modal opened from a drawer is displayed above it. They join the shared stack when theme.overlayStack is set on the MantineProvider theme. An inline Modal or Drawer rendered in the component that calls useModal is displayed below managed modals: render it inside the modal content, open it with useModal/useDrawer or set theme.overlayStack.

Modal content is rendered inside MantineProvider and does not have access to contexts provided below it. Render one Modal.Outlet inside your application providers to render managed modals there. Drawers opened with useDrawer stay in the automatic outlet and are stacked separately from modals rendered by Modal.Outlet, so a modal opened from a managed drawer may be displayed below it. To keep them in one stack, render Drawer.Outlet next to Modal.Outlet inside a provider that sets theme.overlayStack, or do not render outlets:

import { createTheme, Drawer, MantineProvider, Modal } from '@mantine/core';

const theme = createTheme({ overlayStack: true });

function App() {
  return (
    <MantineProvider theme={theme}>
      <RouterProvider>
        <QueryClientProvider>
          {/* Your app here */}
          <Modal.Outlet />
          <Drawer.Outlet />
        </QueryClientProvider>
      </RouterProvider>
    </MantineProvider>
  );
}

Shared modal

To open the same modal from different parts of the application, for example, an authentication modal, call useModal once in a provider component and share the returned object with context. Modal.Outlet renders all modals opened with useModal: render it once, inside every provider the modal content uses, including the shared modal context:

import { createContext, use } from 'react';
import { Button, Group, Modal, PasswordInput, TextInput, useModal, UseModalReturnValue } from '@mantine/core';

const AuthModalContext = createContext<UseModalReturnValue | null>(null);

function useAuthModal() {
  const ctx = use(AuthModalContext);
  if (!ctx) {
    throw new Error('useAuthModal must be used within AuthModalProvider');
  }
  return ctx;
}

function SignInForm() {
  const authModal = useAuthModal();

  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        authModal.close();
      }}
    >
      <TextInput data-autofocus label="Email" placeholder="you@example.com" required />
      <PasswordInput label="Password" placeholder="Your password" required mt="md" />
      <Button type="submit" fullWidth mt="xl">
        Sign in
      </Button>
    </form>
  );
}

function AuthModalProvider({ children }: { children: React.ReactNode }) {
  const modal = useModal({
    title: 'Sign in',
    children: <SignInForm />,
  });

  return (
    <AuthModalContext value={modal}>
      {children}
      <Modal.Outlet />
    </AuthModalContext>
  );
}

function Header() {
  const authModal = useAuthModal();
  return <Button onClick={() => authModal.open()}>Sign in</Button>;
}

function ProtectedAction() {
  const authModal = useAuthModal();
  return (
    <Button variant="default" onClick={() => authModal.open({ title: 'Sign in to continue' })}>
      Download report
    </Button>
  );
}

function Demo() {
  return (
    <AuthModalProvider>
      <Group justify="center">
        <Header />
        <ProtectedAction />
      </Group>
    </AuthModalProvider>
  );
}

Confirm modal

useModal is a building block for application specific modals. The example below creates a useConfirmModal hook that returns a function resolving to true when the user confirms and to false when the modal is canceled or closed:

No result yet

import { useRef, useState } from 'react';
import { Button, Group, Text, useModal, UseModalOptions } from '@mantine/core';

interface ConfirmOptions extends UseModalOptions {
  labels?: { confirm: React.ReactNode; cancel: React.ReactNode };
  confirmColor?: string;
}

function useConfirmModal(defaults: ConfirmOptions = {}) {
  const resolveRef = useRef<((confirmed: boolean) => void) | null>(null);
  const modal = useModal({
    ...defaults,
    onClose: () => {
      resolveRef.current?.(false);
      resolveRef.current = null;
      defaults.onClose?.();
    },
  });

  return (options: ConfirmOptions = {}) =>
    new Promise<boolean>((resolve) => {
      const { labels, confirmColor, children, ...modalProps } = { ...defaults, ...options };
      const settle = (confirmed: boolean) => {
        resolveRef.current = null;
        resolve(confirmed);
        modal.close();
      };

      resolveRef.current = resolve;
      modal.open({
        ...modalProps,
        children: (
          <>
            {children}
            <Group justify="flex-end" mt="md">
              <Button variant="default" onClick={() => settle(false)}>
                {labels?.cancel ?? 'Cancel'}
              </Button>
              <Button color={confirmColor} onClick={() => settle(true)}>
                {labels?.confirm ?? 'Confirm'}
              </Button>
            </Group>
          </>
        ),
      });
    });
}

function Demo() {
  const [result, setResult] = useState('No result yet');
  const confirm = useConfirmModal({ title: 'Please confirm', size: 'sm' });

  const handleDelete = async () => {
    const confirmed = await confirm({
      children: <Text size="sm">This action cannot be undone. Delete the profile?</Text>,
      labels: { confirm: 'Delete profile', cancel: 'Keep it' },
      confirmColor: 'red',
    });

    setResult(confirmed ? 'Profile deleted' : 'Deletion canceled');
  };

  return (
    <Group justify="center">
      <Button color="red" onClick={handleDelete}>
        Delete profile
      </Button>
      <Text size="sm">{result}</Text>
    </Group>
  );
}

Center modal vertically

import { useDisclosure } from '@mantine/hooks';
import { Modal, Button } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  return (
    <>
      <Modal opened={opened} onClose={close} title="Authentication" centered>
        {/* Modal content */}
      </Modal>

      <Button variant="default" onClick={open}>
        Open centered Modal
      </Button>
    </>
  );
}

Remove header

To remove the header, set withCloseButton={false}:

import { useDisclosure } from '@mantine/hooks';
import { Modal, Button } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  return (
    <>
      <Modal opened={opened} onClose={close} withCloseButton={false}>
        Modal without header, press escape or click on overlay to close
      </Modal>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

Change size

You can change the modal width by setting the size prop to a predefined size or any valid width, for example, 55% or 50rem. The Modal width cannot exceed 100vw.

Size auto

Modal with size="auto" will have width that fits its content:

import { useDisclosure, useCounter } from '@mantine/hooks';
import { Modal, Button, Group, Text, Badge } from '@mantine/core';

function Demo() {
  const [opened, { close, open }] = useDisclosure(false);
  const [count, { increment, decrement }] = useCounter(3, { min: 0 });

  const badges = Array(count)
    .fill(0)
    .map((_, index) => <Badge key={index}>Badge {index}</Badge>);

  return (
    <>
      <Modal opened={opened} onClose={close} size="auto" title="Modal size auto">
        <Text>Modal with size auto will fits its content</Text>

        <Group wrap="nowrap" mt="md">
          {badges}
        </Group>

        <Group mt="xl">
          <Button onClick={increment}>Add badge</Button>
          <Button onClick={decrement}>Remove badge</Button>
        </Group>
      </Modal>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

Fullscreen

A fullscreen modal will take the entire screen. It is usually better to change the transition to fade when the fullScreen prop is set:

import { useDisclosure } from '@mantine/hooks';
import { Modal, Button } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  return (
    <>
      <Modal
        opened={opened}
        onClose={close}
        title="This is a fullscreen modal"
        fullScreen
        radius={0}
        transitionProps={{ transition: 'fade', duration: 200 }}
      >
        {/* Modal content */}
      </Modal>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

Fullscreen on small screens

Set the fullScreenBelow prop to make the modal fullscreen only when the viewport is narrower than the given breakpoint:

import { useDisclosure } from '@mantine/hooks';
import { Modal, Button } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  return (
    <>
      <Modal
        opened={opened}
        onClose={close}
        title="Full screen on small screens"
        fullScreenBelow="sm"
        transitionProps={{ transition: 'fade', duration: 200 }}
      >
        {/* Modal content */}
      </Modal>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

fullScreenBelow accepts a key of theme.breakpoints (xs, sm, md, lg, xl), any CSS length (for example, '50em' or '800px') or a number of pixels. The modal reacts to viewport changes while it is opened. The size prop is ignored while the modal is fullscreen. fullScreen takes precedence over fullScreenBelow – it forces fullscreen at any viewport width.

Customize overlay

Modal uses the Overlay component. You can set any props that Overlay supports with overlayProps:

import { useDisclosure } from '@mantine/hooks';
import { Modal, Button } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  return (
    <>
      <Modal
        opened={opened}
        onClose={close}
        title="Authentication"
        overlayProps={{
          backgroundOpacity: 0.55,
          blur: 3,
        }}
      >
        {/* Modal content */}
      </Modal>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

Footer

Use the Modal.Footer component to render a footer with actions:

import { useDisclosure } from '@mantine/hooks';
import { Modal, Button, Group, Text, Box } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  return (
    <>
      <Modal.Root opened={opened} onClose={close}>
        <Modal.Overlay />
        <Modal.Content>
          <Modal.Header>
            <Modal.Title>Terms of service</Modal.Title>
            <Modal.CloseButton />
          </Modal.Header>

          <Modal.Body>
            <Box mih={220}>
              <Text>
                The footer stays pinned to the bottom of the modal even when the body content
                does not fill the entire available space.
              </Text>
            </Box>
          </Modal.Body>

          <Modal.Footer>
            <Group justify="flex-end" w="100%">
              <Button variant="default" onClick={close}>
                Decline
              </Button>
              <Button onClick={close}>Accept</Button>
            </Group>
          </Modal.Footer>
        </Modal.Content>
      </Modal.Root>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

By default, the footer stays pinned to the bottom of the modal while the body scrolls between the header and the footer. When the body content is short, the footer sits at the very bottom with free space above it.

Sticky header and footer

Header and footer stay visible while the body content scrolls. Set stickyHeader={false} or stickyFooter={false} to make them scroll away with the content:

import { useDisclosure } from '@mantine/hooks';
import { Modal, Button, Group, Text } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  return (
    <>
      <Modal.Root opened={opened} onClose={close}>
        <Modal.Overlay />
        <Modal.Content>
          <Modal.Header>
            <Modal.Title>Terms of service</Modal.Title>
            <Modal.CloseButton />
          </Modal.Header>

          <Modal.Body>
            {Array.from({ length: 20 }).map((_, index) => (
              <Text key={index} mb="md">
                Scroll the body to see that the header stays pinned to the top and the footer
                stays pinned to the bottom.
              </Text>
            ))}
          </Modal.Body>

          <Modal.Footer>
            <Group justify="flex-end" w="100%">
              <Button variant="default" onClick={close}>
                Decline
              </Button>
              <Button onClick={close}>Accept</Button>
            </Group>
          </Modal.Footer>
        </Modal.Content>
      </Modal.Root>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

Both props default to true.

Modal with scroll

import { useDisclosure } from '@mantine/hooks';
import { Modal, Button } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  const content = Array(100)
    .fill(0)
    .map((_, index) => <p key={index}>Modal with scroll</p>);

  return (
    <>
      <Modal opened={opened} onClose={close} title="Header is sticky">
        {content}
      </Modal>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

Usage with ScrollArea

import { useDisclosure } from '@mantine/hooks';
import { Modal, Button, ScrollArea } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  const content = Array(100)
    .fill(0)
    .map((_, index) => <p key={index}>Modal with scroll</p>);

  return (
    <>
      <Modal
        opened={opened}
        onClose={close}
        title="Header is sticky"
        scrollAreaComponent={ScrollArea.Autosize}
      >
        {content}
      </Modal>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

Change offsets

Use xOffset/yOffset to configure the horizontal/vertical content offsets:

import { useDisclosure } from '@mantine/hooks';
import { Modal, Button } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  return (
    <>
      <Modal opened={opened} onClose={close} title="Authentication" yOffset="1vh" xOffset={0}>
        {/* Modal content */}
      </Modal>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

Change transitions

Modal is built with the Transition component. Use the transitionProps prop to customize any Transition properties:

import { useState } from 'react';
import { Modal, Group, Button } from '@mantine/core';

function Demo() {
  const [noTransitionOpened, setNoTransitionOpened] = useState(false);
  const [slowTransitionOpened, setSlowTransitionOpened] = useState(false);

  return (
    <>
      <Modal
        opened={slowTransitionOpened}
        onClose={() => setSlowTransitionOpened(false)}
        title="Please consider this"
        transitionProps={{ transition: 'rotate-left' }}
      >
        rotate-left transition
      </Modal>

      <Modal
        opened={noTransitionOpened}
        onClose={() => setNoTransitionOpened(false)}
        title="Please consider this"
        transitionProps={{ transition: 'fade', duration: 600, timingFunction: 'linear' }}
      >
        fade transition 600ms linear transition
      </Modal>

      <Group justify="center">
        <Button onClick={() => setSlowTransitionOpened(true)} variant="default">
          Rotate left transition
        </Button>
        <Button onClick={() => setNoTransitionOpened(true)} variant="default">
          Fade transition
        </Button>
      </Group>
    </>
  );
}

onExitTransitionEnd and onEnterTransitionEnd

The onExitTransitionEnd and onEnterTransitionEnd props can be used to run code after the exit/enter transition is finished. For example, this is useful when you want to clear data after the modal is closed:

import { useState } from 'react';
import { Button, Group, Modal } from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';

function Demo() {
  const [firstOpened, firstHandlers] = useDisclosure(false);
  const [secondOpened, secondHandlers] = useDisclosure(false);
  const [modalData, setModalData] = useState({
    title: '',
    message: '',
  });

  return (
    <>
      <Modal
        opened={firstOpened}
        onClose={() => {
          firstHandlers.close();
          setModalData({ title: '', message: '' });
        }}
        transitionProps={{ duration: 300, exitDuration: 1000, transition: 'fade-down' }}
        title={modalData.title}
      >
        {modalData.message}
      </Modal>
      <Modal
        opened={secondOpened}
        onClose={secondHandlers.close}
        transitionProps={{ duration: 300, exitDuration: 1000, transition: 'fade-down' }}
        onExitTransitionEnd={() => setModalData({ title: '', message: '' })}
        title={modalData.title}
      >
        {modalData.message}
      </Modal>

      <Group>
        <Button
          onClick={() => {
            firstHandlers.open();
            setModalData({ title: 'Edit your profile', message: 'Imagine a form here' });
          }}
          variant="default"
        >
          Clear data in onClose
        </Button>

        <Button
          onClick={() => {
            secondHandlers.open();
            setModalData({ title: 'Edit your profile', message: 'Imagine a form here' });
          }}
          variant="default"
        >
          Clear data in onExitTransitionEnd
        </Button>
      </Group>
    </>
  );
}

Initial focus

Modal uses FocusTrap to trap focus. Add the data-autofocus attribute to the element that should receive initial focus.

import { useDisclosure } from '@mantine/hooks';
import { Modal, Button, TextInput } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  return (
    <>
      <Modal opened={opened} onClose={close} title="Focus demo">
        <TextInput label="First input" placeholder="First input" />
        <TextInput
          data-autofocus
          label="Input with initial focus"
          placeholder="It has data-autofocus attribute"
          mt="md"
        />
      </Modal>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

If you do not want to focus any elements when the modal is opened, use the FocusTrap.InitialFocus component to create a visually hidden element that will receive initial focus:

import { useDisclosure } from '@mantine/hooks';
import { Modal, Button, TextInput, FocusTrap } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  return (
    <>
      <Modal opened={opened} onClose={close} title="Focus demo">
        <FocusTrap.InitialFocus />
        <TextInput label="First input" placeholder="First input" />
        <TextInput
          data-autofocus
          label="Input with initial focus"
          placeholder="It has data-autofocus attribute"
          mt="md"
        />
      </Modal>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

If you do not add the data-autofocus attribute and do not use FocusTrap.InitialFocus, the modal will focus the first focusable element inside it, which is usually the close button.

Control behavior

The following props can be used to control Modal behavior. In most cases, it is not recommended to turn these features off – it will make the component less accessible.

  • trapFocus – determines whether focus should be trapped inside the modal
  • closeOnEscape – determines whether the modal should be closed when the Escape key is pressed
  • closeOnClickOutside – determines whether the modal should be closed when the user clicks on the overlay
  • returnFocus – determines whether focus should be returned to the element that was focused before the modal was opened

Close guard

Use the useModalCloseGuard hook inside modal content to decide whether the user can close the modal. The guard is called when the close button is clicked, Escape is pressed or the overlay is clicked. Return false, or a promise that resolves to false, to keep the modal opened. The hook returns a function that closes the modal through the same guard, use it for Cancel buttons. modal.close() and the opened prop are not affected by guards:

import { useRef } from 'react';
import { Button, Group, Textarea, TextInput, useModal, useModalCloseGuard } from '@mantine/core';
import { useForm } from '@mantine/form';

function NoteForm({ onSave }: { onSave: () => void }) {
  const form = useForm({ initialValues: { title: '', text: '' } });
  const resolveRef = useRef<((discard: boolean) => void) | null>(null);

  const settle = (discard: boolean) => {
    resolveRef.current?.(discard);
    resolveRef.current = null;
  };

  const confirm = useModal({
    title: 'Discard changes?',
    size: 'sm',
    onClose: () => settle(false),
    children: (
      <Group justify="flex-end">
        <Button variant="default" onClick={() => confirm.close()}>
          Keep editing
        </Button>
        <Button
          color="red"
          onClick={() => {
            settle(true);
            confirm.close();
          }}
        >
          Discard
        </Button>
      </Group>
    ),
  });

  // Called before the modal is closed with the close button, Escape or overlay click
  const closeModal = useModalCloseGuard(
    () =>
      !form.isDirty() ||
      new Promise<boolean>((resolve) => {
        resolveRef.current = resolve;
        confirm.open();
      })
  );

  return (
    <form onSubmit={form.onSubmit(onSave)}>
      <TextInput label="Title" placeholder="Title" data-autofocus {...form.getInputProps('title')} />
      <Textarea label="Text" placeholder="Text" mt="md" {...form.getInputProps('text')} />
      <Group justify="flex-end" mt="md">
        <Button variant="default" onClick={closeModal}>
          Cancel
        </Button>
        <Button type="submit">Save</Button>
      </Group>
    </form>
  );
}

function Demo() {
  const modal = useModal({
    title: 'Edit note',
    children: <NoteForm onSave={() => modal.close()} />,
  });

  return <Button onClick={() => modal.open()}>Edit note</Button>;
}

react-remove-scroll settings

Modal uses the react-remove-scroll package to lock scroll. You can pass props down to the RemoveScroll component with removeScrollProps:

import { Modal } from '@mantine/core';

function Demo() {
  return (
    <Modal
      removeScrollProps={{ allowPinchZoom: true }}
      opened
      onClose={() => {}}
    />
  );
}

Change close icon

Use closeButtonProps to customize the close button:

import { XCircleIcon } from '@phosphor-icons/react';
import { useDisclosure } from '@mantine/hooks';
import { Modal, Button } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  return (
    <>
      <Modal
        opened={opened}
        onClose={close}
        title="Authentication"
        closeButtonProps={{
          icon: <XCircleIcon size={20} />,
        }}
      >
        {/* Modal content */}
      </Modal>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

Compound components

You can use the following compound components to have full control over the Modal rendering:

  • Modal.Root – context provider
  • Modal.Overlay – render Overlay
  • Modal.Content – main modal element, should include all modal content
  • Modal.Header – sticky header, usually contains Modal.Title and Modal.CloseButton
  • Modal.Title – h2 element, the aria-labelledby of Modal.Content is pointing to this element, usually rendered inside Modal.Header
  • Modal.CloseButton – close button, usually rendered inside Modal.Header
  • Modal.Body – a place for main content, the aria-describedby of Modal.Content is pointing to this element
  • Modal.Footer – footer element, usually contains action buttons, pinned to the bottom by default (controlled with stickyFooter)
import { useDisclosure } from '@mantine/hooks';
import { Modal, Button } from '@mantine/core';

function Demo() {
  const [opened, { open, close }] = useDisclosure(false);

  return (
    <>
      <Modal.Root opened={opened} onClose={close}>
        <Modal.Overlay />
        <Modal.Content>
          <Modal.Header>
            <Modal.Title>Modal title</Modal.Title>
            <Modal.CloseButton />
          </Modal.Header>
          <Modal.Body>Modal content</Modal.Body>
        </Modal.Content>
      </Modal.Root>

      <Button variant="default" onClick={open}>
        Open modal
      </Button>
    </>
  );
}

Modal.Stack

Use the Modal.Stack component to render multiple modals at the same time. Modal.Stack keeps track of opened modals, manages z-index values, focus trapping, and closeOnEscape behavior. Modal.Stack is designed to be used with the useModalsStack hook.

Differences from using multiple Modal components:

  • Modal.Stack manages z-index values – modals that are opened later will always have a higher z-index value regardless of their order in the DOM
  • Modal.Stack disables focus trap and Escape key handling for all modals except the one that is currently opened
  • All opened modals stay mounted and visible with a stacked depth effect – modals below the top one are scaled down and offset to create a sense of depth
  • Only one overlay is rendered at a time
import { Button, Group, Modal, useModalsStack } from '@mantine/core';

function Demo() {
  const stack = useModalsStack(['delete-page', 'confirm-action', 'really-confirm-action']);

  return (
    <>
      <Modal.Stack>
        <Modal {...stack.register('delete-page')} title="Delete this page?">
          Are you sure you want to delete this page? This action cannot be undone.
          <Group mt="lg" justify="flex-end">
            <Button onClick={stack.closeAll} variant="default">
              Cancel
            </Button>
            <Button onClick={() => stack.open('confirm-action')} color="red">
              Delete
            </Button>
          </Group>
        </Modal>

        <Modal {...stack.register('confirm-action')} title="Confirm action">
          Are you sure you want to perform this action? This action cannot be undone. If you are
          sure, press confirm button below.
          <Group mt="lg" justify="flex-end">
            <Button onClick={stack.closeAll} variant="default">
              Cancel
            </Button>
            <Button onClick={() => stack.open('really-confirm-action')} color="red">
              Confirm
            </Button>
          </Group>
        </Modal>

        <Modal {...stack.register('really-confirm-action')} title="Really confirm action">
          Jokes aside. You have confirmed this action. This is your last chance to cancel it. After
          you press confirm button below, action will be performed and cannot be undone. For real
          this time. Are you sure you want to proceed?
          <Group mt="lg" justify="flex-end">
            <Button onClick={stack.closeAll} variant="default">
              Cancel
            </Button>
            <Button onClick={stack.closeAll} color="red">
              Confirm
            </Button>
          </Group>
        </Modal>
      </Modal.Stack>

      <Button variant="default" onClick={() => stack.open('delete-page')}>
        Open modal
      </Button>
    </>
  );
}

Modals behind the top one stay above the overlay but cannot be interacted with – only the top modal receives pointer events, focus and Escape key presses. Set withStackTransform={false} to disable the stacked depth effect – in this case only the top modal is visible, modals behind it are hidden until the top one is closed.

Use the maxDepth prop (default 5) to control how many stacked modals are visible behind the top one at the same time:

import { Modal, useModalsStack } from '@mantine/core';

function Demo() {
  const stack = useModalsStack(['first', 'second', 'third']);

  return (
    <Modal.Stack maxDepth={3}>
      <Modal {...stack.register('first')}>First</Modal>
      <Modal {...stack.register('second')}>Second</Modal>
      <Modal {...stack.register('third')}>Third</Modal>
    </Modal.Stack>
  );
}

Note that Modal.Stack can only be used with the Modal component. Components built with Modal.Root and other compound components are not compatible with Modal.Stack.

All modals rendered inside Modal.Stack are a part of the stack, stackId prop is required only to connect modal with the useModalsStack hook. To enable stacking for all modals in your application without Modal.Stack, see shared stack section.

useModalsStack hook

The useModalsStack hook provides an easy way to control multiple modals at the same time. It accepts an array of unique modal IDs and returns an object with the following properties:

interface UseModalsStackReturnType<T extends string> {
  // Current opened state of each modal
  state: Record<T, boolean>;

  // Opens modal with the given id
  open: (id: T) => void;

  // Closes modal with the given id
  close: (id: T) => void;

  // Toggles modal with the given id
  toggle: (id: T) => void;

  // Closes all modals within the stack
  closeAll: () => void;

  // Returns props for modal with the given id
  register: (id: T) => {
    opened: boolean;
    onClose: () => void;
    stackId: T;
  };
}

Example of using useModalsStack with the Modal component:

import { Button, Modal, useModalsStack } from '@mantine/core';

function Demo() {
  const stack = useModalsStack(['first', 'second']);

  return (
    <>
      <Modal {...stack.register('first')}>First</Modal>
      <Modal {...stack.register('second')}>Second</Modal>
      <Button onClick={() => stack.open('first')}>Open first</Button>
    </>
  );
}

Shared stack

Set theme.overlayStack to stack all Modal components in your application automatically, without Modal.Stack wrapper and stackId prop:

import { createTheme, MantineProvider } from '@mantine/core';

const theme = createTheme({
  overlayStack: true,
});

function App() {
  return <MantineProvider theme={theme}>{/* Your app here */}</MantineProvider>;
}
import { Button, Group, Modal, useModalStackContext } from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';

function Demo() {
  const [deleteOpened, deleteHandlers] = useDisclosure(false);
  const [confirmOpened, confirmHandlers] = useDisclosure(false);
  const stack = useModalStackContext();

  return (
    <>
      <Modal opened={deleteOpened} onClose={deleteHandlers.close} title="Delete this page?">
        Are you sure you want to delete this page? This action cannot be undone.
        <Group mt="lg" justify="flex-end">
          <Button onClick={deleteHandlers.close} variant="default">
            Cancel
          </Button>
          <Button onClick={confirmHandlers.open} color="red">
            Delete
          </Button>
        </Group>
      </Modal>

      <Modal opened={confirmOpened} onClose={confirmHandlers.close} title="Confirm action">
        Are you sure you want to perform this action? This action cannot be undone. If you are
        sure, press confirm button below.
        <Group mt="lg" justify="flex-end">
          <Button onClick={stack.closeAll} variant="default">
            Cancel
          </Button>
          <Button onClick={stack.closeAll} color="red">
            Confirm
          </Button>
        </Group>
      </Modal>

      <Button variant="default" onClick={deleteHandlers.open}>
        Open modal
      </Button>
    </>
  );
}

With overlayStack enabled, all modals join one shared Modal.Stack. Any modal that is opened while another modal is opened is rendered on top of it: z-index, focus trap, Escape key handling and the overlay are managed for the entire application. Drawer components join their own shared Drawer.Stack – modals and drawers are never stacked visually together, but z-index, focus trap and Escape key handling always follow the topmost opened modal or drawer. When a drawer is opened above modals, the modals are dimmed by the overlay together with the page.

overlayStack accepts an object to configure the shared stacks:

import { createTheme } from '@mantine/core';

const theme = createTheme({
  overlayStack: {
    // Maximum number of stacked modals that remain visible behind the top one, 5 by default
    maxDepth: 3,

    // true by default, false disables the depth effect and shows only the top modal
    withStackTransform: false,
  },
});

When theme.overlayStack is set, Modal.Stack does not create a separate stack – modals rendered inside it become a part of the shared stack, maxDepth and withStackTransform props of Modal.Stack are ignored. useModalsStack hook can still be used to manage opened state of several modals.

stackId values inside the shared stack are scoped per Modal.Stack instance – separate Modal.Stack components may reuse the same ids (for example, two components that both call useModalsStack(['first', 'second'])) without conflicts. useModalStackContext called inside such Modal.Stack returns only the modals of that Modal.Stack, and its close and closeAll handlers do not affect modals of other Modal.Stack instances.

Use useModalStackContext hook to access the shared stack (or the closest Modal.Stack) from any component:

import { Button, useModalStackContext } from '@mantine/core';

function CloseAllButton() {
  const stack = useModalStackContext();
  return <Button onClick={stack.closeAll}>Close all modals ({stack.stack.length})</Button>;
}

useModalStackContext returns an object with the following properties:

interface UseModalStackContextReturnType {
  // Ids of opened modals, the last item is the top modal
  stack: string[];

  // Id of the top modal, undefined if no modals are opened
  currentId: string | undefined;

  // Calls onClose of the modal with the given id
  close: (id: string) => void;

  // Calls onClose of all opened modals, starting from the top one
  closeAll: () => void;
}

Fixed elements offset

The Modal component uses the react-remove-scroll package to lock scroll. To properly size these elements, add a className to them (documentation):

import { RemoveScroll } from '@mantine/core';

function Demo() {
  return (
    <>
      <div className={RemoveScroll.classNames.fullWidth}>
        width: 100%
      </div>
      <div className={RemoveScroll.classNames.zeroRight}>
        right: 0
      </div>
    </>
  );
}

Accessibility

Use title to name the dialog and closeButtonProps to label its close button:

import { Modal } from '@mantine/core';

function Demo({ opened, onClose }: { opened: boolean; onClose: () => void }) {
  return (
    <Modal
      opened={opened}
      onClose={onClose}
      title="Account settings"
      closeButtonProps={{ 'aria-label': 'Close account settings' }}
    />
  );
}