A hook to trap focus inside a specific element so the user can't tab outside it. Supports granular control over focus behaviors via options.

Parameters:
NameTypeDescription
activeboolean

Whether the element that will trap the focus is active or not.

optionsobject

Options for the focus trap hook.

Properties
NameTypeDescription
ariaModalboolean

Whether to apply role and aria-modal attributes. Default false.

ariaRoleTypestring

Role type when ariaModal is true: 'dialog' or 'alertdialog'. Default 'dialog'.

disableAriaHiderboolean

Whether to disable aria hiding. Default false.

focusTrapIdstring | symbol

Optional ID for this trap. When omitted, a stable random ID is used. When set, call setReturnFocusTarget(element, id) from outside to override.

focusKeystring | number

Optional key that when changed, resets focus state and re-applies focus.

focusSelectorstring

Selector or element to focus initially.

tabScopingEnabledboolean

Whether to trap Tab key within container. Default true.

Since
  • 1.1.3
Author
  • https://github.com/charlie-tango
Returns:

A callback ref to attach to the element that will trap the focus.

Type: 
function
Examples
import React from 'react'
import { useFocusTrap } from '@gravityforms/react-utils';

const Component = () => {
 const ref = useFocusTrap()
 return (
  <div ref={ref}>
    <button>Trapped to the button</button>
  </div>
 )
}

export default Component
// With granular control (e.g., for a pinnable flyout)
const trapRef = useFocusTrap(isOpen, {
  tabScopingEnabled: !isPinned,
  ariaModal: !isPinned,
});
// Flyout with two buttons: override return focus when switching content
import { useFocusTrap, setReturnFocusTarget } from '@gravityforms/react-utils';
const FLYOUT_TRAP_ID = 'my-flyout';
const trapRef = useFocusTrap(isOpen, { focusTrapId: FLYOUT_TRAP_ID });
// When button 2 opens the same flyout with different content:
setReturnFocusTarget(button2Ref.current, FLYOUT_TRAP_ID);

Methods

(inner) applyInitialFocus(node) → {void}

Applies initial focus to the first focusable element.

Parameters:
NameTypeDescription
nodeHTMLElement

The container node.

Since
  • 5.1.1
Returns:
Type: 
void

(inner) setAria() → {void}

Sets the aria attributes.

Since
  • 5.1.2
Returns:
Type: 
void

(inner) unsetAria() → {void}

Unsets the aria attributes.

Since
  • 5.1.2
Returns:
Type: 
void