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.
| Name | Type | Description | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
active | boolean | Whether the element that will trap the focus is active or not. | ||||||||||||||||||||||||
options | object | Options for the focus trap hook. Properties
|
- Since
- 1.1.3
- Source
A callback ref to attach to the element that will trap the focus.
- Type:
- function
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.
| Name | Type | Description |
|---|---|---|
node | HTMLElement | The container node. |
- Since
- 5.1.1
- Source
- Type:
- void
(inner) setAria() → {void}
Sets the aria attributes.
- Since
- 5.1.2
- Source
- Type:
- void
(inner) unsetAria() → {void}
Unsets the aria attributes.
- Since
- 5.1.2
- Source
- Type:
- void