useDialogFocus

Move, trap and restore focus for a dialog.

useDialogFocus(open, containerRef, initialFocusRef?)

Focus management for dialogs. When open becomes true it moves focus into the container (to initialFocusRef if given, else the element marked data-autofocus, otherwise the first focusable one - which in a Modal or Drawer is the Close button), keeps Tab and Shift+Tab inside it, and returns focus to the element that opened it when it closes. Modal, Drawer and CommandPalette use it; for a ready-made wrapper see `FocusTrap`.

Focus starts in the field, Tab stays inside, and returns to the button on close.

API

  • openboolean

    Whether the dialog is open.

  • containerRefRefObject<HTMLElement>

    Ref of the dialog element.

See also:ModalDrawerCommandPaletteFocusTrap