use-focus-return

Captures last focused element on the page and returns focus to it once given condition is met

Import

Usage

use-focus-return automatically returns focus to the last focused element when a given condition is met. For example, it is used in Modal component to restore focus after the modal was closed.

Close the modal with the Escape key and see how focus returns to the button after the modal closes:

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 onClick={open}>Open modal</Button>
    </>
  );
}

In most cases, you should use this hook with use-focus-trap.

import { useFocusReturn } from '@mantine/hooks';

useFocusReturn({
  // Is region with focus trap active?
  // When it activates hook saves document.activeElement to the internal state
  // and focuses this element once focus trap is deactivated
  opened: false,

  // Determines whether focus should be returned automatically, true by default
  shouldReturnFocus: true,
});

If shouldReturnFocus option is set to false you can call returned function to focus last active element:

import { useFocusReturn } from '@mantine/hooks';

const returnFocus = useFocusReturn({
  opened: false,
  shouldReturnFocus: false,
});

// ... later
returnFocus();

Definition

function useFocusReturn(options: {
  opened: boolean;
  shouldReturnFocus?: boolean;
}): () => void;