본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

FocusTrap

원문 보기 위키 갱신

FocusTrap는 키보드 포커스를 자신의 컨테이너 안에 가두는 styled가 없는 컴포넌트예요. 모달 영역을 만들 때 키보드 포커스가 정의된 경계 안에 머물도록 보장해 줘요.

출처: 문서

본문

기능 (Features)

  • 포커스 순환: Tab은 마지막 포커스 가능 요소에서 첫 번째로, Shift+Tab은 첫 번째에서 마지막으로 감싸요
  • initialFocusRef, [autofocus], [data-autofocus]를 지원하는 마운트 시 자동 포커스
  • onEscape 콜백을 통한 Escape 키 처리
  • MutationObserver가 DOM 변경을 감지하고 적절히 포커스를 다시 맞춰 줘요
  • 보이지 않는 포커스 경계를 위해 VisuallyHidden 센티널 요소를 사용해요

사용법 (Usage)

import { FocusTrap } from 'primereact/focustrap';
<FocusTrap>
    <input type="text" />
    <button type="submit"></button>
</FocusTrap>

동작 (Behavior)

다형적 렌더링 (Polymorphic Rendering)

as를 사용해 렌더링되는 컨테이너 요소를 바꿀 수 있어요. 기본값은 div예요.

<FocusTrap as="section">...</FocusTrap>

렌더 함수 자식 (Render Function Children)

<FocusTrap>{(instance) => <div>Trapped: {String(instance.props.trapped)}</div>}</FocusTrap>

패스 스루 (Pass Through)

<DocPTViewer name="focustrap-pt" components={['FocusTrap']} />

API

FocusTrap

Attribute Value
data-focus-trap Present on the container when active
Label Type Description
root FocusTrapPassThroughType<HTMLAttributes> Used to pass attributes to the root's DOM element.
hiddenElement FocusTrapPassThroughType<HTMLAttributes> Used to pass attributes to the hiddenElement's DOM element.
pcVisibleHidden FocusTrapPassThroughType<HTMLAttributes> Used to pass attributes to the pcVisibleHidden's DOM element.

접근성 (Accessibility)

스크린 리더 (Screen Reader)

FocusTrap는 콘텐츠 앞뒤에 VisuallyHidden 센티널 요소를 배치해 포커스를 순환시켜요. 이 센티널들은 role="presentation"과 aria-hidden="true"를 가져서 스크린 리더가 무시해요.

키보드 지원 (Keyboard Support)

Key Function
tab Moves focus to the next focusable element inside the trap. Wraps to the first when at the end.
shift + tab Moves focus to the previous focusable element inside the trap. Wraps to the last when at the start.
escape Calls the onEscape callback when defined.

더 알아보기 (Learn more)