@accessible/drawer

中文文档
3.0.2发布于 2020/08/11MITTypeScriptESM + CJS近 30 天下载 4140

🅰 An accessible and versatile drawer component for React

原始使用文档
文档目录15 节
  1. Features
  2. Quick Start
  3. API
  4. Components
  5. Hooks
  6. <Drawer>
  7. useA11yTarget(target, options?)
  8. <Target>
  9. useA11yTrigger(target, options?)
  10. <Trigger>
  11. useA11yCloseButton(target, options?)
  12. <CloseButton>
  13. useDrawer()
  14. DrawerContextValue
  15. LICENSE

<Drawer>

Bundlephobia Types Code coverage Build status NPM Version MIT License

npm i @accessible/drawer

An accessible and versatile drawer component for React

Features

  • Style-agnostic You can use this component with the styling library of your choice. It works with CSS-in-JS, SASS, plain CSS, plain style objects, anything!
  • Portal-friendly The drawer target will render into React portals of your choice when configured to do so.
  • a11y/aria-compliant This component works with screen readers out of the box and manages focus for you.

Quick Start

Check out the example on CodeSandbox

import * as React from 'react'
import * as Drawer from '@accessible/drawer'

const Component = () => (
  <Drawer.Drawer>
    <Drawer.Trigger>
      <button>Open me</button>
    </Drawer.Trigger>

    <Drawer.Target>
      <div className='my-drawer'>
        <Drawer.CloseButton>
          <button>Close me</button>
        </Drawer.CloseButton>

        <div>I've been revealed!</div>
      </div>
    </Drawer.Target>
  </Drawer.Drawer>
)

API

Components

ComponentDescription
<Drawer>This component creates the context for your drawer target and trigger and contains some configuration options.
<Target>This component wraps any React element and turns it into a drawer target.
<Trigger>This component wraps any React element and turns it into a drawer trigger.
<CloseButton>This is a convenience component that wraps any React element and adds an onClick handler to close the drawer.

Hooks

HookDescription
useDrawer()This hook provides the value of the drawer's DrawerContextValue object.
useA11yTarget()A React hook for creating a headless drawer target to WAI-ARIA authoring practices.
useA11yTrigger()A React hook for creating a headless drawer trigger to WAI-ARIA authoring practices.
useA11yCloseButton()A React hook for creating a headless close button to WAI-ARIA authoring practices.

<Drawer>

This component creates the context for your drawer target and trigger and contains some configuration options.

Props

PropTypeDefaultRequired?Description
defaultOpenbooleanfalseNoThis sets the default open state of the drawer. By default the drawer is closed.
openbooleanundefinedNoThis creates a controlled drawer component where the open state of the drawer is controlled by this property.
onChange(open: boolean) => voidundefinedNoThis callback is invoked any time the open state of the drawer changes.
idstringundefinedNoBy default this component creates a unique id for you, as it is required for certain aria attributes. Supplying an id here overrides the auto id feature.
childrenReact.ReactNodeundefinedNoYour drawer contents and any other children.

useA11yTarget(target, options?)

A React hook for creating a headless drawer target to WAI-ARIA authoring practices.

Arguments

ArgumentTypeRequired?Description
targetReact.RefObject<T> | T | nullYesA React ref or HTML element
optionsUseA11yTargetOptionsNoConfiguration options

UseA11yTargetOptions

export interface UseA11yTargetOptions {
  /**
   * Sets the placement of the drawer menu
   * @default "left"
   */
  placement?: 'top' | 'right' | 'bottom' | 'left'
  /**
   * Adds this class name to props when the drawer is open
   */
  openClass?: string
  /**
   * Adds this class name to props when the drawer is closed
   */
  closedClass?: string
  /**
   * Adds this style to props when the drawer is open
   */
  openStyle?: React.CSSProperties
  /**
   * Adds this style to props when the drawer is closed
   */
  closedStyle?: React.CSSProperties
  /**
   * Prevents the `window` from scrolling when the target is
   * focused after opening.
   */
  preventScroll?: boolean
  /**
   * When `true`, this closes the target element when the `Escape`
   * key is pressed.
   * @default true
   */
  closeOnEscape?: boolean
}

Returns

type A11yProps = {
  readonly 'aria-hidden': boolean
  readonly id: string | undefined
  readonly className: string | undefined
  readonly style: {
    readonly visibility: 'hidden' | 'visible'
  } & React.CSSProperties
} & {
  readonly style:
    | ({
        readonly visibility: 'hidden' | 'visible'
      } & React.CSSProperties & {
          readonly position: 'fixed'
          readonly top: 0
          readonly right: 0
          readonly bottom: 'auto'
          readonly left: 0
          readonly transform: 'translate3d(0, -100%, 0)'
        })
    | ({
        readonly visibility: 'hidden' | 'visible'
      } & React.CSSProperties & {
          readonly position: 'fixed'
          readonly top: 0
          readonly right: 0
          readonly bottom: 0
          readonly left: 'auto'
          readonly transform: 'translate3d(100%, 0, 0)'
        })
    | ({
        readonly visibility: 'hidden' | 'visible'
      } & React.CSSProperties & {
          readonly position: 'fixed'
          readonly top: 'auto'
          readonly right: 0
          readonly bottom: 0
          readonly left: 0
          readonly transform: 'translate3d(0, 100%, 0)'
        })
    | ({
        readonly visibility: 'hidden' | 'visible'
      } & React.CSSProperties & {
          readonly position: 'fixed'
          readonly top: 0
          readonly right: 'auto'
          readonly bottom: 0
          readonly left: 0
          readonly transform: 'translate3d(-100%, 0, 0)'
        })
}

Example

import * as React from 'react'
import {useA11yTarget} from '@accessible/drawer'

const MyTarget = () => {
  const ref = React.useRef(null)
  const a11yProps = useA11yTarget(ref, {preventScroll: true})

  return (
    <div ref={ref} {...a11yProps}>
      I am the drawer content
    </div>
  )
}

<Target>

This component wraps any React element and turns it into a drawer target.

Props

PropTypeDefaultRequired?Description
placement"top" | "right" | "bottom" | "left"falseNoWhen true this will render the drawer into a React portal with the id #portals. You can render it into any portal by providing its query selector here, e.g. #foobar, [data-portal=true], or .foobar.
portalboolean | string | PortalizePropsfalseNoWhen true this will render the drawer into a React portal with the id #portals. You can render it into any portal by providing its query selector here, e.g. #foobar, [data-portal=true], or .foobar.
closeOnEscapebooleantrueNoBy default the drawer will close when the Escape key is pressed. You can turn this off by providing false here.
closedClassstringundefinedNoThis class name will be applied to the child element when the drawer is closed.
openClassstringundefinedNoThis class name will be applied to the child element when the drawer is open.
closedStyleReact.CSSPropertiesundefinedNoThese styles will be applied to the child element when the drawer is closed in addition to the default styles that set the target's visibility.
openStyleReact.CSSPropertiesundefinedNoThese styles name will be applied to the child element when the drawer is open in addition to the default styles that set the target's visibility.
preventScrollbooleanfalseNoWhen true this will prevent your browser from scrolling the document to bring the newly-focused tab into view.
childrenReact.ReactElementundefinedYesThe child is cloned by this component and has aria attributes injected into its props as well as the events defined above.

Example

<Target>
  <div className='alert'>Alert</div>
</Target>

// <div
//   class="alert"
//   aria-hidden="true"
//   id="🅰12"
//   style="visibility: hidden;"
// >
//   Alert
// </div>

useA11yTrigger(target, options?)

A React hook for creating a headless drawer trigger to WAI-ARIA authoring practices. In addition to providing accessibility props to your component, this hook will add events for interoperability between actual elements and fake ones e.g. and

Arguments

ArgumentTypeRequired?Description
targetReact.RefObject<T> | T | nullYesA React ref or HTML element
optionsUseA11yTriggerOptionsNoConfiguration options

UseA11yTriggerOptions

export interface UseA11yTriggerOptions {
  /**
   * Adds this class name to props when the drawer is open
   */
  openClass?: string
  /**
   * Adds this class name to props when the drawer is closed
   */
  closedClass?: string
  /**
   * Adds this style to props when the drawer is open
   */
  openStyle?: React.CSSProperties
  /**
   * Adds this style to props when the drawer is closed
   */
  closedStyle?: React.CSSProperties
  /**
   * Adds an onClick handler in addition to the default one that
   * toggles the drawer's open state.
   */
  onClick?: (e: MouseEvent) => any
}

Returns

interface A11yProps<E extends React.MouseEvent<any, MouseEvent>> {
  readonly 'aria-controls': string | undefined
  readonly 'aria-expanded': boolean
  readonly role: 'button'
  readonly tabIndex: 0
  readonly className: string | undefined
  readonly style: React.CSSProperties | undefined
}

Example

import * as React from 'react'
import {useA11yTrigger} from '@accessible/drawer'

const MyTrigger = () => {
  const ref = React.useRef(null)
  const a11yProps = useA11yTrigger(ref, {
    openClass: 'open',
    closedClass: 'closed',
  })

  return (
    <button ref={ref} {...a11yProps}>
      Clicking me toggles the drawer content
    </button>
  )
}

<Trigger>

This component wraps any React element and adds an onClick handler which toggles the open state of the drawer target.

Props

PropTypeDefaultRequired?Description
closedClassstringundefinedNoThis class name will be applied to the child element when the drawer is closed.
openClassstringundefinedNoThis class name will be applied to the child element when the drawer is open.
closedStyleReact.CSSPropertiesundefinedNoThese styles will be applied to the child element when the drawer is closed.
openStyleReact.CSSPropertiesundefinedNoThese styles name will be applied to the child element when the drawer is open.
childrenReact.ReactElementundefinedYesThe child is cloned by this component and has aria attributes injected into its props as well as the events defined above.
<Trigger on='click'>
  <button className='my-button'>Open me!</button>
</Trigger>

// <button
//   class="my-button"
//   aria-controls="🅰12"
//   aria-expanded="false"
// >
//   Open me!
// </button>

useA11yCloseButton(target, options?)

A React hook for creating a headless close button to WAI-ARIA authoring practices. In addition to providing accessibility props to your component, this hook will add events for interoperability between actual elements and fake ones e.g. and

Arguments

ArgumentTypeRequired?Description
targetReact.RefObject<T> | T | nullYesA React ref or HTML element
optionsUseA11yCloseButtonOptionsNoConfiguration options

UseA11yCloseButtonOptions

export interface UseA11yCloseButtonOptions {
  /**
   * Adds an onClick handler in addition to the default one that
   * closes the drawer.
   */
  onClick?: (e: MouseEvent) => any
}

Returns

interface A11yProps<E extends React.MouseEvent<any, MouseEvent>> {
  readonly 'aria-controls': string | undefined
  readonly 'aria-expanded': boolean
  readonly 'aria-label': 'Close'
  readonly role: 'button'
  readonly tabIndex: 0
}

Example

import * as React from 'react'
import {useA11yCloseButton} from '@accessible/drawer'

const MyTrigger = () => {
  const ref = React.useRef(null)
  const a11yProps = useA11yCloseButton(ref, {
    onClick: () => console.log('Closing!'),
  })

  return (
    <button ref={ref} {...a11yProps}>
      Clicking me closes the drawer content
    </button>
  )
}

<CloseButton>

This is a convenience component that wraps any React element and adds an onClick handler which closes the drawer.

Props

PropTypeDefaultRequired?Description
childrenReact.ReactElementundefinedYesThe child is cloned by this component and has aria attributes injected into its props as well as the events defined above.
<CloseButton>
  <button className='my-button'>Close me</button>
</CloseButton>

// <button
//   class="my-button"
//   aria-controls="drawer--12"
//   aria-expanded="false"
// >
//   Close me
// </button>

useDrawer()

This hook provides the value of the drawer's DrawerContextValue object

DrawerContextValue

export interface DrawerContextValue {
  /**
   * The open state of the drawer
   */
  isOpen: boolean
  /**
   * Opens the drawer
   */
  open: () => void
  /**
   * Closes the drawer
   */
  close: () => void
  /**
   * Toggles the open state of the drawer
   */
  toggle: () => void
  /**
   * A unique ID for the drawer target
   */
  id?: string
}

Example

const Component = () => {
  const {open, close, toggle, isOpen} = useDrawer()
  return <button onClick={toggle}>Toggle the drawer</button>
}

LICENSE

MIT

版本与发布记录

@accessible/drawer 共发布 19 个版本,首次发布于 2019/12/18;过去 12 个月发布了 0 个版本。

版本发布日期距今
3.0.2latest2020/08/116 年前
3.0.12020/08/116 年前
3.0.02020/07/206 年前
2.2.12020/05/306 年前
2.2.02020/05/306 年前
2.1.42020/01/176 年前

关于 @accessible/drawer 的常见问题

@accessible/drawer 是什么?

🅰 An accessible and versatile drawer component for React

如何安装 @accessible/drawer?

在项目目录运行 npm install @accessible/drawer,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=16.8)、react-dom(>=16.8)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@accessible/drawer 支持 TypeScript 吗?

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

@accessible/drawer 支持 ESM 还是 CommonJS?

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

@accessible/drawer 可以商用吗?

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

@accessible/drawer 的下载量有多少?

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

@accessible/drawer 还在维护吗?

最新版本 3.0.2 发布于 2020/08/11(6 年前);至今共发布 19 个版本,其中过去 12 个月发布了 0 个;首次发布于 2019/12/18。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。