useFocusTrap
지정된 요소 안으로 키보드 포커스를 가두는 훅이에요. 모달이나 오버레이처럼 포커스를 특정 영역에 고정해야 할 때 사용해요. disabled, initialFocusRef, restoreFocusOnCleanUp, returnFocusRef 같은 옵션으로 시작 포커스와 해제 후 포커스 복원 동작을 제어할 수 있어요.
출처: 문서
본문
지정된 요소 안으로 포커스를 가둬요. 이 예제들에서는 활성 포커스 트랩 바깥을 클릭하면 포커스 트랩이 비활성화돼요. 이건 기본 동작이 아니에요. 사용자가 예제와 상호작용한 뒤 포커스 트랩을 끄는 걸 잊어도 페이지의 포커스 동작이 망가지지 않도록 하기 위한 꼼수일 뿐이에요.
예제
기본 (Default)
import React from 'react'
import {useFocusTrap, useOnOutsideClick} from '@primer/react'
export default function Default() {
const [trapEnabled, setTrapEnabled] = React.useState(false)
const {containerRef} = useFocusTrap({disabled: !trapEnabled})
/* START: not needed for using `useFocusTrap`
This is just a workaround so focus behavior is not broken on the page if a
user forgets to disable the focus trap after interacting with the example.
*/
const exampleContainerRef = React.useRef<HTMLDivElement>(null)
useOnOutsideClick({
onClickOutside: () => {
setTrapEnabled(false)
},
containerRef: exampleContainerRef,
})
/* END: not needed for using `useFocusTrap` */
return (
<div ref={exampleContainerRef} style={{display: 'flex', flexDirection: 'column', gap: '1rem'}}>
<button onClick={() => setTrapEnabled(!trapEnabled)}>{trapEnabled ? 'Disable' : 'Enable'} trap</button>
<button>Before trap</button>
<div
ref={containerRef as React.RefObject<HTMLDivElement | null>}
style={{
border: '1px solid',
margin: '1rem',
padding: '1rem',
display: 'flex',
flexDirection: 'column',
gap: '1rem',
}}
>
{trapEnabled ? (
<div>
Focus trap is <strong>enabled</strong>. Focus will be trapped in here.
</div>
) : (
<div>
Focus trap is <strong>disabled</strong>. Focus will <strong>not</strong> be trapped in here.
</div>
)}
<button>First trapped</button>
<button>Second trapped</button>
<button>Third trapped</button>
</div>
<button>After trap</button>
</div>
)
}
커스텀 첫 포커스 요소
트랩이 켜졌을 때 첫 번째로 포커스를 받을 요소를 initialFocusRef로 지정할 수 있어요.
import React from 'react'
import {useFocusTrap, useOnOutsideClick} from '@primer/react'
export default function Default() {
const [trapEnabled, setTrapEnabled] = React.useState(false)
const initialFocusRef = React.useRef<HTMLButtonElement>(null)
const {containerRef} = useFocusTrap({disabled: !trapEnabled, initialFocusRef})
/* START: not needed for using `useFocusTrap` */
const exampleContainerRef = React.useRef<HTMLDivElement>(null)
useOnOutsideClick({
onClickOutside: () => {
setTrapEnabled(false)
},
containerRef: exampleContainerRef,
})
/* END: not needed for using `useFocusTrap` */
return (
<div ref={exampleContainerRef} style={{display: 'flex', flexDirection: 'column', gap: '1rem'}}>
<button onClick={() => setTrapEnabled(!trapEnabled)}>{trapEnabled ? 'Disable' : 'Enable'} trap</button>
<button>Before trap</button>
<div
ref={containerRef as React.RefObject<HTMLDivElement | null>}
style={{border: '1px solid', margin: '1rem', padding: '1rem', display: 'flex', flexDirection: 'column', gap: '1rem'}}
>
{trapEnabled ? (
<div>
Focus trap is <strong>enabled</strong>. Focus will be trapped in here.
</div>
) : (
<div>
Focus trap is <strong>disabled</strong>. Focus will <strong>not</strong> be trapped in here.
</div>
)}
<button>First trapped</button>
<button ref={initialFocusRef}>Second trapped (focus goes here first)</button>
<button>Third trapped</button>
</div>
<button>After trap</button>
</div>
)
}
포커스 트랩이 꺼진 후 이전 포커스 요소로 돌아가기
트랩 안에 포커스가 있는 상태에서 Escape 키를 누르면 포커스 트랩이 꺼져요. restoreFocusOnCleanUp을 true로 설정하면 포커스 트랩이 꺼질 때, 트랩에 들어가기 전에 포커스가 있던 요소로 포커스가 돌아가요.
import React from 'react'
import {useFocusTrap, useOnOutsideClick} from '@primer/react'
export default function Toggle() {
const [trapEnabled, setTrapEnabled] = React.useState(false)
const {containerRef} = useFocusTrap({disabled: !trapEnabled, restoreFocusOnCleanUp: true})
/* Pressing the "Escape" key will turn the focus trap off */
React.useEffect(() => {
if (!exampleContainerRef.current?.contains(document.activeElement)) {
return
}
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
setTrapEnabled(false)
}
}
window.addEventListener('keydown', handleKeyDown)
return () => {
window.removeEventListener('keydown', handleKeyDown)
}
})
/* START: not needed for using `useFocusTrap` */
const exampleContainerRef = React.useRef<HTMLDivElement>(null)
useOnOutsideClick({
onClickOutside: () => {
setTrapEnabled(false)
},
containerRef: exampleContainerRef,
})
/* END: not needed for using `useFocusTrap` */
return (
<div ref={exampleContainerRef} style={{display: 'flex', flexDirection: 'column', gap: '1rem'}}>
<button onClick={() => setTrapEnabled(!trapEnabled)}>{trapEnabled ? 'Disable' : 'Enable'} trap</button>
<button>Before trap</button>
<div ref={containerRef as React.RefObject<HTMLDivElement | null>} style={{border: '1px solid', margin: '1rem', padding: '1rem', display: 'flex', flexDirection: 'column', gap: '1rem'}}>
{trapEnabled ? (
<div>
Focus trap is <strong>enabled</strong>. Focus will be trapped in here.
</div>
) : (
<div>
Focus trap is <strong>disabled</strong>. Focus will <strong>not</strong> be trapped in here.
</div>
)}
<button>First trapped</button>
<button>Second trapped</button>
<button>Third trapped</button>
</div>
<button>After trap</button>
</div>
)
}
포커스 트랩이 꺼진 후 특정 요소로 돌아가기
트랩 안에 포커스가 있는 상태에서 Escape 키를 누르면 포커스 트랩이 꺼져요. returnFocusRef를 지정하면 포커스 트랩이 꺼질 때 항상 같은 요소로 포커스가 돌아가요.
import React from 'react'
import {useFocusTrap, useOnOutsideClick} from '@primer/react'
export default function Toggle() {
const [trapEnabled, setTrapEnabled] = React.useState(false)
const returnFocusRef = React.useRef<HTMLButtonElement>(null)
const {containerRef} = useFocusTrap({
disabled: !trapEnabled,
// This ternary protects the element with `returnFocusRef` from being focused
// as soon as the docs page is loaded.
returnFocusRef: trapEnabled ? returnFocusRef : undefined,
})
/* Pressing the "Escape" key will turn the focus trap off */
React.useEffect(() => {
if (!exampleContainerRef.current?.contains(document.activeElement)) {
return
}
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
setTrapEnabled(false)
}
}
window.addEventListener('keydown', handleKeyDown)
return () => {
window.removeEventListener('keydown', handleKeyDown)
}
})
/* START: not needed for using `useFocusTrap` */
const exampleContainerRef = React.useRef<HTMLDivElement>(null)
useOnOutsideClick({
onClickOutside: () => {
setTrapEnabled(false)
},
containerRef: exampleContainerRef,
})
/* END: not needed for using `useFocusTrap` */
return (
<div ref={exampleContainerRef} style={{display: 'flex', flexDirection: 'column', gap: '1rem'}}>
<button onClick={() => setTrapEnabled(!trapEnabled)}>{trapEnabled ? 'Disable' : 'Enable'} trap</button>
<button ref={returnFocusRef}>Disabling the trap moves focus here</button>
<button>Before trap</button>
<div ref={containerRef as React.RefObject<HTMLDivElement | null>} style={{border: '1px solid', margin: '1rem', padding: '1rem', display: 'flex', flexDirection: 'column', gap: '1rem'}}>
{trapEnabled ? (
<div>
Focus trap is <strong>enabled</strong>. Focus will be trapped in here.
</div>
) : (
<div>
Focus trap is <strong>disabled</strong>. Focus will <strong>not</strong> be trapped in here.
</div>
)}
<button>First trapped</button>
<button>Second trapped</button>
<button>Third trapped</button>
</div>
<button>After trap</button>
</div>
)
}
API
useFocusTrap의 전체 API는 원문 페이지의 "API" 섹션에서 확인할 수 있어요.
관련 링크
@primer/behaviors의focusTrap
더 알아보기 (Learn more)
useFocusTrap({containerRef})으로 반환된containerRef를 트랩할 요소에 연결하세요.disabled로 켜고 끄고,initialFocusRef로 시작 포커스 요소를 지정해요.restoreFocusOnCleanUp은 이전 포커스로,returnFocusRef는 지정한 요소로 포커스를 되돌려요.- 바깥 클릭으로 끄는 건 기본 동작이 아니에요. 필요하면
useOnOutsideClick과 조합하세요.