Focus Trap (포커스 트랩)
FocusTrap 컴포넌트는 지정된 컨테이너 안에 키보드 포커스를 가두는 접근성 유틸리티예요. 모달 인터페이스처럼 사용자의 주의가 필요한 요소에서 포커스가 벗어나지 않도록 유지해 줘요.
출처: 문서
본문
동기 (Motivation)
포커스 트래핑은 모달 인터페이스와 사용자의 주의가 필요한 기타 인터랙티브 요소에 필수적이에요.
FocusTrap 컴포넌트는 명시적으로 해제되기 전까지 키보드 포커스가 지정된 컨테이너 안에 머물도록 보장해서 접근성을 유지하는 데 도움을 줘요.
예제 (Examples)
import { FocusTrap } from '@ark-ui/react/focus-trap'
import { useState } from 'react'
export const Basic = () => {
const [trapped, setTrapped] = useState(false)
return (
<>
<button onClick={() => setTrapped(true)}>Start Trap</button>
<FocusTrap returnFocusOnDeactivate={false} disabled={!trapped}>
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '1rem',
paddingBlock: '1rem',
}}
>
<input type="text" placeholder="input" />
<textarea placeholder="textarea" />
<button onClick={() => setTrapped(false)}>End Trap</button>
</div>
</FocusTrap>
</>
)
}
자동 포커스 (Autofocus)
포커스 트랩은 autofocus 속성이 있는 요소를 존중해 줘요.
import { FocusTrap } from '@ark-ui/react/focus-trap'
import { useRef, useState } from 'react'
export const Autofocus = () => {
const [trapped, setTrapped] = useState(false)
const toggle = () => setTrapped((c) => !c)
const buttonRef = useRef<HTMLButtonElement | null>(null)
const getButtonNode = () => {
const node = buttonRef.current
if (!node) throw new Error('Button not found')
return node
}
return (
<div>
<button ref={buttonRef} onClick={toggle}>
{trapped ? 'End Trap' : 'Start Trap'}
</button>
{trapped && (
<FocusTrap disabled={!trapped} setReturnFocus={getButtonNode}>
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '1rem',
paddingBlock: '1rem',
}}
>
<input type="text" placeholder="Regular input" />
{/* biome-ignore lint/a11y/noAutofocus: intentional */}
<input type="text" placeholder="Autofocused input" autoFocus />
<button onClick={() => setTrapped(false)}>End Trap</button>
</div>
</FocusTrap>
)}
</div>
)
}
초기 포커스 (Initial Focus)
initialFocus prop을 사용해 트랩이 활성화될 때 초기 포커스를 받을 요소를 설정할 수 있어요.
import { FocusTrap } from '@ark-ui/react/focus-trap'
import { useRef, useState } from 'react'
export const InitialFocus = () => {
const [trapped, setTrapped] = useState(false)
const toggle = () => setTrapped((c) => !c)
const inputRef = useRef<HTMLInputElement>(null)
return (
<div>
<button onClick={toggle}>{trapped ? 'End Trap' : 'Start Trap'}</button>
<FocusTrap disabled={!trapped} initialFocus={() => inputRef.current}>
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '1rem',
paddingBlock: '1rem',
}}
>
<input type="text" placeholder="First input" />
<input ref={inputRef} type="text" placeholder="Second input (initial focus)" />
<textarea placeholder="textarea" />
<button onClick={() => setTrapped(false)}>End Trap</button>
</div>
</FocusTrap>
</div>
)
}
API 레퍼런스 (API Reference)
FocusTrap
Props
asChild
Type: boolean
Required: false
Default Value: undefined
Description: Use the provided child element as the default rendered element, combining their props and behavior.
disabled
Type: boolean
Required: false
Default Value: undefined
Description: Whether the focus trap is disabled.
fallbackFocus
Type: FocusTarget
Required: false
Default Value: undefined
Description: By default, an error will be thrown if the focus trap contains no
elements in its tab order. With this option you can specify a
fallback element to programmatically receive focus if no other
tabbable elements are found. For example, you may want a popover's
<div> to receive focus if the popover's content includes no
tabbable elements. *Make sure the fallback element has a negative
tabindex so it can be programmatically focused.
NOTE: If initialFocus is false (or a function that returns false),
this function will not be called when the trap is activated, and no element
will be initially focused. This function may still be called while the trap
is active if things change such that there are no longer any tabbable nodes
in the trap.
initialFocus
Type: VoidFunction | FocusTargetOrFalse
Required: false
Default Value: undefined
Description: By default, when a focus trap is activated the first element in the
focus trap's tab order will receive focus. With this option you can
specify a different element to receive that initial focus, or use false
for no initially focused element at all.
NOTE: Setting this option to false (or a function that returns false)
will prevent the fallbackFocus option from being used.
Setting this option to undefined (or a function that returns undefined)
will result in the default behavior.
onActivate
Type: VoidFunction
Required: false
Default Value: undefined
Description: A function that will be called before sending focus to the
target element upon activation.
onDeactivate
Type: VoidFunction
Required: false
Default Value: undefined
Description: A function that will be called before sending focus to the
trigger element upon deactivation.
persistentElements
Type: (() => Element | null)[]
Required: false
Default Value: undefined
Description: Additional elements to treat as part of the trap, for portalled content
not discoverable via aria-controls/aria-expanded (see followControlledElements).
returnFocusOnDeactivate
Type: boolean
Required: false
Default Value: undefined
Description: Default: true. If false, when the trap is deactivated,
focus will not return to the element that had focus before activation.
setReturnFocus
Type: type ONLY_FOR_FORMAT = FocusTargetValueOrFalse | ((nodeFocusedBeforeActivation: HTMLElement | SVGElement) => FocusTargetValueOrFalse)
Required: false
Default Value: undefined
Description: By default, focus trap on deactivation will return to the element
that was focused before activation.