@collapsed/react

中文文档
5.1.0发布于 2024/12/24MITTypeScriptESM + CJS近 30 天下载 1982

A React custom-hook for creating flexible and accessible expand/collapse components.

原始使用文档
文档目录9 节
  1. Features
  2. Demo
  3. Installation
  4. Usage
  5. Simple Usage
  6. Control it yourself
  7. API
  8. Alternative Solutions
  9. FAQ

NOTE

You're probably looking for react-collapsed. This package (alongside @collapsed/core) is a WIP rewrite to create a Vanilla JS core.


@collapsed/react (useCollapse)

A React hook for creating accessible expand/collapse components. Animates the height using CSS transitions from 0 to auto.

Features

  • Handles the height of animations of your elements, auto included!
  • You control the UI - useCollapse provides the necessary props, you control the styles and the elements.
  • Accessible out of the box - no need to worry if your collapse/expand component is accessible, since this takes care of it for you!
  • No animation framework required! Simply powered by CSS animations
  • Written in TypeScript

Demo

See the demo site!

CodeSandbox demo

Installation

$ npm i @collapsed/react

Usage

Simple Usage

import React from "react";
import { useCollapse } from "@collapsed/react";

function Demo() {
  const { getCollapseProps, getToggleProps, isExpanded } = useCollapse();

  return (
    <div>
      <button {...getToggleProps()}>
        {isExpanded ? "Collapse" : "Expand"}
      </button>
      <section {...getCollapseProps()}>Collapsed content 🙈</section>
    </div>
  );
}

Control it yourself

import React, { useState } from "react";
import { useCollapse } from "@collapsed/react";

function Demo() {
  const [isExpanded, setExpanded] = useState(false);
  const { getCollapseProps, getToggleProps } = useCollapse({ isExpanded });

  return (
    <div>
      <button
        {...getToggleProps({
          onClick: () => setExpanded((prevExpanded) => !prevExpanded),
        })}
      >
        {isExpanded ? "Collapse" : "Expand"}
      </button>
      <section {...getCollapseProps()}>Collapsed content 🙈</section>
    </div>
  );
}

API

useCollapse takes the following options:

interface UseCollapseOptions {
  /** If true, the disclosure is expanded. */
  isExpanded?: boolean;
  /**
   * If true, the disclosure is expanded when it initially mounts.
   * @default false
   */
  defaultExpanded?: boolean;
  /** Handler called when the disclosure expands or collapses */
  onExpandedChange?: (state: boolean) => void;
  /** Handler called at each stage of the animation. */
  onTransitionStateChange?: (
    state:
      | "expandStart"
      | "expanding"
      | "expandEnd"
      | "collapseStart"
      | "collapsing"
      | "collapseEnd",
  ) => void;
  /** Timing function for the transition */
  easing?: string;
  /**
   * Duration of the expand/collapse animation.
   * If 'auto', the duration will be calculated based on the height of the collapse element
   */
  duration?: "auto" | number;
  /** Height in pixels that the collapse element collapses to */
  collapsedHeight?: number;
  /**
   * Unique identifier used to for associating elements appropriately for accessibility.
   */
  id?: string;
}

And returns the following API:

interface CollapseAPI {
  isExpanded: boolean;
  setExpanded: (update: boolean | ((prev: boolean) => boolean)) => void;
  getToggleProps: <T extends HTMLElement>(
    props?: React.ComponentPropsWithoutRef<T> & { refKey?: string },
  ) => React.ComponentPropsWithRef<T>;
  getCollapseProps: <T extends HTMLElement>(
    props?: React.ComponentPropsWithoutRef<T> & { refKey?: string },
  ) => React.ComponentPropsWithRef<T>;
}

Alternative Solutions

  • react-spring - JavaScript animation based library that can potentially have smoother animations. Requires a bit more work to create an accessible collapse component.
  • react-animate-height - Another library that uses CSS transitions to animate to any height. It provides components, not a hook.

FAQ

When I apply vertical padding to the component that gets getCollapseProps, the animation is janky and it doesn't collapse all the way. What gives?

The collapse works by manipulating the height property. If an element has vertical padding, that padding expandes the size of the element, even if it has height: 0; overflow: hidden.

To avoid this, simply move that padding from the element to an element directly nested within in.

// from
<div {...getCollapseProps({style: {padding: 20}})}
  This will do weird things
</div>

// to
<div {...getCollapseProps()}
  <div style={{padding: 20}}>
    Much better!
  </div>
</div>

版本与发布记录

@collapsed/react 共发布 6 个版本,首次发布于 2023/01/16;过去 12 个月发布了 0 个版本。

版本发布日期距今
5.1.0latest2024/12/241.9 年前
5.0.02024/06/222 年前
4.1.0-experimental.79f518cexperimental2023/03/023 年前
4.0.12023/01/253 年前
4.0.02023/01/163 年前
4.0.0-beta.1next2023/01/163 年前

关于 @collapsed/react 的常见问题

@collapsed/react 是什么?

A React custom-hook for creating flexible and accessible expand/collapse components.

如何安装 @collapsed/react?

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

@collapsed/react 支持 TypeScript 吗?

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

@collapsed/react 支持 ESM 还是 CommonJS?

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

@collapsed/react 可以商用吗?

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

@collapsed/react 的下载量有多少?

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

@collapsed/react 还在维护吗?

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