Skip to content

useFocusTrap

Category
Export Size
576 B
Package
@reause/integrations
Last Changed
5 days ago

Reactive wrapper for focus-trap.

For more information on what options can be passed, see createOptions in the focus-trap documentation.

Demo

Install

bash
npm i focus-trap@^7

Usage

Basic Usage

tsx
import { 
useFocusTrap
} from '@reause/integrations'
import {
useRef
} from 'react'
function
Component
() {
const
target
=
useRef
<HTMLDivElement>(null)
const {
hasFocus
,
activate
,
deactivate
} =
useFocusTrap
(
target
)
return ( <
div
>
<
button
onClick={() =>
activate
()}>
Activate </button> <div ref={
target
}>
<
span
>
Has Focus: {
String
(hasFocus)}
</span> <input type="text" /> <
button
onClick={() => deactivate()}>
Deactivate </button> </div> </div> ) }

Multiple Targets

tsx
const 
targetOne
=
useRef
<HTMLDivElement>(null)
const
targetTwo
=
useRef
<HTMLDivElement>(null)
const {
hasFocus
,
activate
,
deactivate
} =
useFocusTrap
([
targetOne
,
targetTwo
])

Selector String

tsx
const { 
hasFocus
,
activate
,
deactivate
} =
useFocusTrap
('#dialog')

Automatically Focus

tsx
const 
target
=
useRef
<HTMLDivElement>(null)
const {
hasFocus
,
activate
,
deactivate
} =
useFocusTrap
(
target
, {
immediate
: true })
// the trap is activated as soon as the target element is available

Conditional Rendering

This function can't properly activate focus on elements with conditional rendering. This is because they do not exist in the DOM at the time of the focus activation. To solve this you need to activate on the next tick.

tsx
const [
show
,
setShow
] =
useState
(false)
const
target
=
useRef
<HTMLDivElement>(null)
const {
activate
} =
useFocusTrap
(
target
, {
immediate
: true })
function
reveal
() {
setShow
(true)
setTimeout
(
activate
, 0)
}

Type Declarations

ts
export interface UseFocusTrapOptions extends FocusTrap.Options {
    immediate?: boolean;
    onActivate?: (params?: ActivateOptions) => void;
    onDeactivate?: (params?: DeactivateOptions) => void;
}

export interface UseFocusTrapReturn {
    hasFocus: boolean;
    isPaused: boolean;
    activate: (opts?: ActivateOptions) => void;
    deactivate: (opts?: DeactivateOptions) => void;
    pause: () => void;
    unpause: () => void;
}

type ActivateOptions = NonNullable<Parameters<FocusTrap.FocusTrap['activate']>[0]>

type DeactivateOptions = NonNullable<Parameters<FocusTrap.FocusTrap['deactivate']>[0]>

type FocusTrapTarget = string | RefObject<MaybeElement>

export function useFocusTrap(target: FocusTrapTarget | FocusTrapTarget[], options?: UseFocusTrapOptions): UseFocusTrapReturn

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
0c413 - fix(integrations): resolve useFocusTrap audit findings (#801)
c659a - feat(integrations): add useFocusTrap (#134)

Released under the MIT License. v0.1.8