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.

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,
});

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