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

useFocusZone

원문 보기 위키 갱신

'Tab'이 아닌 키(주로 화살표 키)로 포커스를 이동할 수 있는 컨테이너를 지정하는 훅이에요. WAI-ARIA Authoring Practices 문서의 Section 6에 나오는 여러 패턴(예: 메뉴의 항목들 사이를 위/아래 화살표로 이동)을 구현하는 데 유용해요. 내부적으로 포커스 가능 요소의 tabindex를 조정하고, 컨테이너에 키 입력을 처리하는 이벤트 리스너를 설치하는 방식으로 동작해요.

출처: 문서

본문

'Tab'이 아닌 키로 포커스를 이동할 수 있는 컨테이너를 지정해요. 이 훅은 WAI-ARIA Authoring Practices 문서의 Section 6에 나오는 많은 패턴을 구현하는 데 유용해요. 가장 흔한 사용 사례는 메뉴의 항목들처럼 서로 관련된 요소 사이를 화살표 키(위/아래 또는 왼쪽/오른쪽)로 이동하게 하는 거예요.

높은 수준에서 보면 useFocusZone은 포커스 가능 요소의 tabindex 속성을 조정하고, 관련 키 입력에 반응하도록 컨테이너에 이벤트 리스너를 설치하는 방식으로 동작해요.

Focusability: 어떤 요소가 Focus Zone에 참여하나요?

포커스 가능(Focusable) 요소는 Tab 키로 정상적으로 포커스가 되거나, 유효한 tabindex 속성("-1" 포함)을 가진 요소예요. 요소가 포커스 존에 참여하게 하는 가장 쉬운 방법은 tabindex="-1" 속성을 적용하는 거예요.

포커스 존에 진입하기

기본적으로 포커스가 포커스 존에 진입하면, 그 포커스 존 안에서 가장 최근에 포커스됐던 요소가 포커스를 받아요. 이전에 포커스된 요소가 없거나 그 요소가 제거됐다면, 포커스 이동 방향과 무관하게 포커스 존 안의 첫 번째 포커스 가능 요소로 포커스가 되돌아가요. focusInStrategy 옵션으로 이 동작을 바꿀 수 있어요.

올바른 포커스 진입 동작을 고르는 방법은 ARIA Authoring Practices 문서의 "6.6 Keyboard Navigation Inside Components"를 참고하세요.

DOM focus와 active descendant

useFocusZone 훅은 DOM Focus와 Active descendant 두 가지 모드를 지원해요.

  • DOM Focus는 기본 모드이고 대부분의 경우 가장 필요한 모드예요. 키로 포커스를 이동하면 포커스를 받을 요소에 .focus()를 직접 호출해요. 그 결과 document.activeElement가 이 새 요소로 설정되고, :focus와 :focus-within을 통해 필요한 스타일을 받아요.
  • Active descendant 모드는 DOM 포커스를 이동하지 않아요. 대신 포커스는 control 요소에 남아 있고, 그 요소의 aria-activedescendant 속성이 관련 요소의 ID로 설정돼요. :focus 스타일이 적용되지 않고 focus 이벤트도 발생하지 않으므로, active descendant가 바뀔 때 필요한 스타일이나 로직을 처리하려면 onActivedescendantChanged 콜백을 제공할 수 있어요.

Active descendant 포커스 패턴에 대한 자세한 내용은 ARIA Authoring Practices 문서의 "6.6.2 Managing Focus in Composites Using aria-activedescendant"를 참고하세요.

예제

기본 (Default)

포커스 존 안에서 위/아래 화살표 키로 포커스를 이동할 수 있어요.

import React from 'react'
import {useFocusZone} from '@primer/react'

export default function Default() {
  const {containerRef} = useFocusZone()

  return (
    <>
      <button>Before zone</button>
      <div
        ref={containerRef as React.RefObject<HTMLDivElement | null>}
        style={{
          border: '1px solid',
          margin: '1rem',
          padding: '1rem',
          display: 'flex',
          flexDirection: 'column',
          gap: '1rem',
        }}
      >
        <p>Focus can be moved with up and down arrow keys in here.</p>
        <button>First</button>
        <button>Second</button>
        <button>Third</button>
      </div>
      <button>After zone</button>
    </>
  )
}

커스텀 키 바인딩

bindKeys 옵션으로 포커스를 이동하는 데 쓸 키를 정해요. 이 예제는 bindKeys를 써서 J와 K 키로 포커스를 이동하게 하는 방법을 보여줘요.

import React from 'react'
import {useFocusZone} from '@primer/react'
import {FocusKeys} from '@primer/behaviors'

export default function BindKeys() {
  const {containerRef} = useFocusZone({bindKeys: FocusKeys.JK})

  return (
    <>
      <button>Before zone</button>
      <div
        ref={containerRef as React.RefObject<HTMLDivElement | null>}
        style={{border: '1px solid', margin: '1rem', padding: '1rem', display: 'flex', gap: '1rem'}}
      >
        <p>Focus can be moved with J and K keys.</p>
        <button>First</button>
        <button>Second</button>
        <button>Third</button>
      </div>
      <button>After zone</button>
    </>
  )
}

커스텀 첫 포커스 요소

focusInStrategy를 "closest"로 설정하면 포커스 이동 방향에 따라 컨테이너의 첫 번째 또는 마지막 포커스 가능 요소에 포커스가 갈 수 있어요. 예를 들어 shift+tab으로 컨테이너에 포커스가 오면 마지막 요소에, 일반 tab이면 첫 번째 요소에 포커스가 가요.

그 외에는 초기 포커스를 받을 커스텀 요소를 고르는 콜백을 제공할 수 있어요. 목록에서 "선택된(selected)" 항목에 포커스를 주고 싶다면 이 방식이 유용해요.

focusInStrategy: closest

  • "First"는 "Before zone"에서 포커스가 진입할 때 먼저 포커스되고, "Third"는 "After zone"에서 진입할 때 먼저 포커스돼요.

focusInStrategy: first

  • "First"는 포커스가 진입할 때 항상 먼저 포커스돼요.

focusInStrategy: previous

  • 가장 최근에 포커스됐던 요소가 포커스 진입 시 먼저 포커스돼요.
import React from 'react'
import {useFocusZone} from '@primer/react'

export default function FocusInStrategy() {
  const {containerRef: containerRefClosest} = useFocusZone({focusInStrategy: 'closest'})
  const {containerRef: containerRefFirst} = useFocusZone({focusInStrategy: 'first'})
  const {containerRef: containerRefPrevious} = useFocusZone({focusInStrategy: 'previous'})

  return (
    <>
      <div style={{margin: '1rem 0'}}>
        <h4>focusInStrategy: closest</h4>
        <button>Before zone</button>
        <div ref={containerRefClosest as React.RefObject<HTMLDivElement | null>} style={{border: '1px solid', margin: '1rem', padding: '1rem', display: 'flex', flexDirection: 'column', gap: '1rem'}}>
          <p>Focus can be moved with up and down arrow keys in here.</p>
          <button>First</button>
          <button>Second</button>
          <button>Third</button>
        </div>
        <button>After zone</button>
      </div>
      <div style={{margin: '1rem 0'}}>
        <h4>focusInStrategy: first</h4>
        <button>Before zone</button>
        <div ref={containerRefFirst as React.RefObject<HTMLDivElement | null>} style={{border: '1px solid', margin: '1rem', padding: '1rem', display: 'flex', flexDirection: 'column', gap: '1rem'}}>
          <p>Focus can be moved with up and down arrow keys in here.</p>
          <button>First</button>
          <button>Second</button>
          <button>Third</button>
        </div>
        <button>After zone</button>
      </div>
      <div style={{margin: '1rem 0'}}>
        <h4>focusInStrategy: previous</h4>
        <button>Before zone</button>
        <div ref={containerRefPrevious as React.RefObject<HTMLDivElement | null>} style={{border: '1px solid', margin: '1rem', padding: '1rem', display: 'flex', flexDirection: 'column', gap: '1rem'}}>
          <p>Focus can be moved with up and down arrow keys in here.</p>
          <button>First</button>
          <button>Second</button>
          <button>Third</button>
        </div>
        <button>After zone</button>
      </div>
    </>
  )
}

커스텀 포커스 이탈 동작

포커스는 (Tab 키를 쓰는 경우를 제외하면) 컨테이너의 마지막 요소를 넘어 이동할 수 없어요. focusOutBehavior 옵션으로 마지막에서 첫 번째 요소로(또는 그 반대로) 포커스가 돌아가게(wrap) 할 수 있어요.

더 커스터마이즈된 포커스 이동이 필요하면, 다음 포커스를 받을 요소를 정하는 커스텀 콜백을 제공할 수 있어요.

focusInStrategy: stop

  • 포커스 이동이 처음과 끝에서 멈춰요.

focusInStrategy: wrap

  • 처음이나 끝에 도달하면 다시 첫 번째 또는 마지막 요소로 돌아가요.
import React from 'react'
import {useFocusZone} from '@primer/react'

export default function FocusOutBehavior() {
  const {containerRef: containerRefStop} = useFocusZone({focusOutBehavior: 'stop'})
  const {containerRef: containerRefWrap} = useFocusZone({focusOutBehavior: 'wrap'})

  return (
    <>
      <div style={{margin: '1rem 0'}}>
        <h4>focusInStrategy: stop</h4>
        <button>Before zone</button>
        <div ref={containerRefStop as React.RefObject<HTMLDivElement | null>} style={{border: '1px solid', margin: '1rem', padding: '1rem', display: 'flex', flexDirection: 'column', gap: '1rem'}}>
          <p>Focus movement stops at the beginning and end.</p>
          <button>First</button>
          <button>Second</button>
          <button>Third</button>
        </div>
        <button>After zone</button>
      </div>
      <div style={{margin: '1rem 0'}}>
        <h4>focusInStrategy: wrap</h4>
        <button>Before zone</button>
        <div ref={containerRefWrap as React.RefObject<HTMLDivElement | null>} style={{border: '1px solid', margin: '1rem', padding: '1rem', display: 'flex', flexDirection: 'column', gap: '1rem'}}>
          <p>Focus movement will wrap back around to the first or last element after reaching the beginning or end.</p>
          <button>First</button>
          <button>Second</button>
          <button>Third</button>
        </div>
        <button>After zone</button>
      </div>
    </>
  )
}

커스텀 포커스 이동

getNextFocusable 콜백을 제공하면 다음 포커스 요소를 직접 정할 수 있어요. 아래 예제는 3x3 그리드에서 왼쪽/오른쪽 화살표로 행(row)을, 위/아래 화살표로 열(column)을 이동하게 만들어요.

import React from 'react'
import {useFocusZone} from '@primer/react'

function getSiblingIndex(element: Element) {
  let child: Element | null = element
  let i = 0
  while ((child = child.previousElementSibling) != null) {
    ++i
  }
  return i
}

export default function GetNextFocusable() {
  const containerRef = React.useRef<HTMLElement>(null)

  const getNextFocusable = React.useCallback(
    (
      direction: 'previous' | 'next' | 'start' | 'end',
      from: Element | undefined,
      event: KeyboardEvent,
    ): HTMLElement | undefined => {
      const toEnd = direction === 'start' || direction === 'end'
      if (from && containerRef.current) {
        const currentIndex = getSiblingIndex(from)
        let nextIndex = currentIndex
        if (['End', 'ArrowRight'].includes(event.key)) {
          while (nextIndex % 3 !== 2) {
            nextIndex += 1
            if (!toEnd) {
              break
            }
          }
        }
        if (['Home', 'ArrowLeft'].includes(event.key)) {
          while (nextIndex % 3 !== 0) {
            nextIndex -= 1
            if (!toEnd) {
              break
            }
          }
        }
        if (event.key === 'ArrowUp') {
          while (nextIndex - 3 >= 0) {
            nextIndex -= 3
            if (!toEnd) {
              break
            }
          }
        }
        if (event.key === 'ArrowDown') {
          while (nextIndex + 3 < 9) {
            nextIndex += 3
            if (!toEnd) {
              break
            }
          }
        }
        return containerRef.current.children[nextIndex] as HTMLElement
      }
    },
    [containerRef],
  )

  useFocusZone({containerRef, getNextFocusable})

  return (
    <>
      <button>Before zone</button>
      <div style={{border: '1px solid', margin: '1rem', padding: '1rem'}}>
        <p>
          Focus can be moved in rows with left and right arrow keys. Focus can be moved in columns with the up and down
          arrow keys.
        </p>
        <div
          ref={containerRef as React.RefObject<HTMLDivElement | null>}
          style={{
            display: 'grid',
            gridTemplateRows: 'repeat(3, 1fr)',
            gridTemplateColumns: 'repeat(3, 1fr)',
            gap: '0.5rem',
          }}
        >
          <button>First</button>
          <button>Second</button>
          <button>Third</button>
          <button>Fourth</button>
          <button>Fifth</button>
          <button>Sixth</button>
          <button>Seventh</button>
          <button>Eighth</button>
          <button>Ninth</button>
        </div>
      </div>
      <button>After zone</button>
    </>
  )
}

요소가 포커스되는 것 방지하기

포커스 가능 요소가 포커스 존에 참여하지 않게 하려면 focusableElementFilter를 제공할 수 있어요. 아래 예제에서는 tagName === 'BUTTON'인 요소만 포커스 존에 참여하도록 해서, 링크는 Tab 키로만 접근할 수 있어요.

import React from 'react'
import {Link, useFocusZone} from '@primer/react'

export default function FocusableElementFilter() {
  const {containerRef} = useFocusZone({focusableElementFilter: (element: Element) => element.tagName === 'BUTTON'})

  return (
    <>
      <button>Before zone</button>
      <div
        ref={containerRef as React.RefObject<HTMLDivElement | null>}
        style={{border: '1px solid', margin: '1rem', padding: '1rem', display: 'flex', flexDirection: 'column', gap: '1rem'}}
      >
        <p>
          Focus can be moved with up and down arrow keys in here, but <em>links will be skipped</em> unless using the
          Tab key.
        </p>
        <button>First</button>
        <Link href="#someLink">Link one</Link>
        <button>Second</button>
        <Link href="#someLink">Link two</Link>
        <button>Third</button>
      </div>
      <button>After zone</button>
    </>
  )
}

컨테이너가 포커스를 이동할 때 스크롤되는 것 방지하기

포커스 존 안에서 키로 포커스를 이동할 때 컨테이너가 스크롤되지 않도록 방지할 수 있어요. 이 옵션에 대한 전체 예제는 원문 페이지를 참고하세요.

포커스 존 비활성화하기

disabled 옵션으로 포커스 존을 켜고 끌 수 있어요. 비활성화하면 포커스 이동 키 처리가 멈춰요. 전체 예제는 원문 페이지를 참고하세요.

Active descendant 동작

Active descendant 모드에서 onActivedescendantChanged 콜백으로 active descendant가 바뀔 때 스타일이나 로직을 처리해요. 전체 예제는 원문 페이지를 참고하세요.

중첩된 포커스 존

포커스 존은 서로 중첩될 수 있어요. 중첩된 포커스 존의 전체 예제는 원문 페이지를 참고하세요.

API

useFocusZone의 전체 API와 옵션은 원문 페이지의 "API" 섹션에서 확인할 수 있어요.

관련 링크

  • @primer/behaviors의 Focus Keys(FocusKeys) 및 관련 동작

더 알아보기 (Learn more)

  • useFocusZone({containerRef})로 반환된 containerRef를 포커스 존으로 만들 컨테이너에 연결하세요.
  • bindKeys(기본 화살표 키, J/K 등), focusInStrategy(closest/first/previous), focusOutBehavior(stop/wrap)로 이동 규칙을 조정해요.
  • DOM Focus(기본)와 Active descendant(aria-activedescendant) 두 모드를 지원해요.
  • focusableElementFilter로 특정 요소를 존에서 제외하고, disabled로 존을 끌 수 있어요.
  • 메뉴, 콤보박스 등 WAI-ARIA 컴포짓 패턴 구현에 주로 쓰여요.