@charlietango/use-focus-trap

中文文档
1.4.0发布于 2022/04/15MITTypeScriptESM + CJS零依赖近 30 天下载 1.2万

Trap keyboard focus inside a DOM element, to prevent the user navigating outside a modal

此软件包已被标记为弃用

No longer supported. Migrate to a new solution for support, or copy the code into the project

原始使用文档
文档目录5 节
  1. Installation
  2. API
  3. Options
  4. Example
  5. Creating a Modal

useFocusTrap

Trap keyboard focus inside a DOM element, to prevent the user navigating outside a modal. When using this, make sure to combine it with a fixed position <Backdrop> that prevents the mouse from clicking input elements.

Checkout the Storybook demo.

Installation

yarn add @charlietango/use-focus-trap

API

const ref = useFocusTrap(active, options)

The useFocusTrap hook returns a ref that you should assign to the DOM element that needs to trap focus. Anything outside that element, will no longer be able to receive focus.

You can toggle the trap by setting the active boolean. By default it's activated once the ref is assigned.

Options

The focus trap accepts an object with these optional options, that give you a bit more control.

NameTypeDefaultRequiredDescription
focusSelectorstring / HTMLElementundefinedfalseAssign focus when activated to the element matching this selector - or a specific element you supply. By default focus will be set to the first valid tab target.
disableAriaHiderbooleanfalsefalseDisables setting aria-hidden on other elements inside the document.body while the trap is active.

Example

import React from 'react'
import useFocusTrap from '@charlietango/use-focus-trap'

const Component = () => {
  const ref = useFocusTrap()
  return (
    <div ref={ref}>
      <button>Trapped to the button</button>
    </div>
  )
}

export default Component

Creating a Modal

When using this hook to create a Modal, there are still a few things you need to handle, that's outside the scope of this hook:

  • Trap focus
  • Close on escape
  • Close on backdrop clicked

BaseModal.tsx

This is the base component for creating a <Modal />. It receives an onRequestClose method, that can be triggered to tell the containing component to update it's state to close the modal. It doesn't contain a <Backdrop />, but that would be a absolute positioned component, that when clicked triggers the onRequestClose method.

import React, { useEffect } from 'react'
import ReactDOM from 'react-dom'
import useFocusTrap from '@charlietango/use-focus-trap'
import styled from 'styled-components'

type Props = {
  onRequestClose?: () => void
  children?: React.ReactNode
  isOpen: boolean
  className?: string
}

const Wrapper = styled.div`
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 5;
`

function BaseModal({ children, isOpen, onRequestClose, className }: Props) {
  const ref = useFocusTrap()

  function handleKeyDown(event: KeyboardEvent) {
    if (event.key === 'Escape') {
      if (onRequestClose) onRequestClose()
    }
  }

  useEffect(() => {
    if (isOpen) {
      document.addEventListener('keydown', handleKeyDown)
      return () => {
        document.removeEventListener('keydown', handleKeyDown)
      }
    }

    return
  }, [isOpen])

  const modal = (
    <Wrapper
      ref={ref}
      style={{ pointerEvents: !isOpen ? 'none' : undefined }}
      role="dialog"
      className={className}
    >
      {children}
    </Wrapper>
  )

  return ReactDOM.createPortal(modal, window.document.body)
}

BaseModal.displayName = 'BaseModal'
BaseModal.defaultProps = {}

export default BaseModal

版本与发布记录

@charlietango/use-focus-trap 共发布 16 个版本,首次发布于 2019/03/01;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.4.0latest2022/04/154 年前
1.3.02020/10/196 年前
1.2.122020/09/236 年前
1.2.112020/06/096 年前
1.2.102020/01/296 年前
1.2.92020/01/286 年前

关于 @charlietango/use-focus-trap 的常见问题

@charlietango/use-focus-trap 是什么?

Trap keyboard focus inside a DOM element, to prevent the user navigating outside a modal注意:该包已被作者标记为弃用——No longer supported. Migrate to a new solution for support, or copy the code into the project

如何安装 @charlietango/use-focus-trap?

在项目目录运行 npm install @charlietango/use-focus-trap,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0)、react-dom(^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@charlietango/use-focus-trap 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@charlietango/use-focus-trap 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@charlietango/use-focus-trap 可以商用吗?

@charlietango/use-focus-trap 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@charlietango/use-focus-trap 的下载量有多少?

根据 npm 官方下载统计,@charlietango/use-focus-trap 在 2026/10/10 – 2026/11/08 这 30 天内被下载 11,921 次,日均约 397 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@charlietango/use-focus-trap 还在维护吗?

最新版本 1.4.0 发布于 2022/04/15(4 年前);至今共发布 16 个版本,其中过去 12 个月发布了 0 个;首次发布于 2019/03/01。作者已将其标记为弃用,新项目建议寻找替代方案。