auto-animate

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AutoAnimate

AutoAnimate

Status: Production Ready ✅ Last Updated: 2025-11-07 Dependencies: None (works with any React setup) Latest Versions: @formkit/auto-animate@0.9.0

状态:已就绪可用于生产环境 ✅ 最后更新时间:2025-11-07 依赖项:无(可适配任意React环境) 最新版本:@formkit/auto-animate@0.9.0

Quick Start (2 Minutes)

快速上手(2分钟)

1. Install AutoAnimate

1. 安装AutoAnimate

bash
bun add @formkit/auto-animate
Why this matters:
  • Only 3.28 KB gzipped (vs 22 KB for Motion)
  • Zero dependencies
  • Framework-agnostic (React, Vue, Svelte, vanilla JS)
bash
bun add @formkit/auto-animate
重要性说明:
  • 仅3.28 KB压缩后体积(对比Motion的22 KB)
  • 无依赖项
  • 框架无关(支持React、Vue、Svelte、原生JS)

2. Add to Your Component

2. 添加到组件中

tsx
import { useAutoAnimate } from "@formkit/auto-animate/react";

export function MyList() {
  const [parent] = useAutoAnimate(); // 1. Get ref

  return (
    <ul ref={parent}> {/* 2. Attach to parent */}
      {items.map(item => (
        <li key={item.id}>{item.text}</li> {/* 3. That's it! */}
      ))}
    </ul>
  );
}
CRITICAL:
  • ✅ Always use unique, stable keys for list items
  • ✅ Parent element must always be rendered (not conditional)
  • ✅ AutoAnimate respects
    prefers-reduced-motion
    automatically
  • ✅ Works on add, remove, AND reorder operations
tsx
import { useAutoAnimate } from "@formkit/auto-animate/react";

export function MyList() {
  const [parent] = useAutoAnimate(); // 1. Get ref

  return (
    <ul ref={parent}> {/* 2. Attach to parent */}
      {items.map(item => (
        <li key={item.id}>{item.text}</li> {/* 3. That's it! */}
      ))}
    </ul>
  );
}
关键注意事项:
  • ✅ 始终为列表项使用唯一且稳定的key
  • ✅ 父元素必须始终渲染(不能是条件渲染)
  • ✅ AutoAnimate会自动遵循
    prefers-reduced-motion
    设置
  • ✅ 支持添加、移除和重新排序操作

3. Use in Production (SSR-Safe)

3. 生产环境使用(SSR安全)

For Cloudflare Workers or Next.js:
tsx
// Use client-only import to prevent SSR errors
import { useState, useEffect } from "react";

export function useAutoAnimateSafe<T extends HTMLElement>() {
  const [parent, setParent] = useState<T | null>(null);

  useEffect(() => {
    if (typeof window !== "undefined" && parent) {
      import("@formkit/auto-animate").then(({ default: autoAnimate }) => {
        autoAnimate(parent);
      });
    }
  }, [parent]);

  return [parent, setParent] as const;
}

适用于Cloudflare Workers或Next.js:
tsx
// Use client-only import to prevent SSR errors
import { useState, useEffect } from "react";

export function useAutoAnimateSafe<T extends HTMLElement>() {
  const [parent, setParent] = useState<T | null>(null);

  useEffect(() => {
    if (typeof window !== "undefined" && parent) {
      import("@formkit/auto-animate").then(({ default: autoAnimate }) => {
        autoAnimate(parent);
      });
    }
  }, [parent]);

  return [parent, setParent] as const;
}

Known Issues Prevention

已知问题预防

This skill prevents 10+ documented issues:
本指南可预防**10+**个已记录的问题:

Issue #1: SSR/Next.js Import Errors

问题1:SSR/Next.js导入错误

Error: "Can't import the named export 'useEffect' from non EcmaScript module" Source: https://github.com/formkit/auto-animate/issues/55 Why It Happens: AutoAnimate uses DOM APIs not available on server Prevention: Use dynamic imports (see
templates/vite-ssr-safe.tsx
)
错误信息:"无法从非ECMAScript模块导入命名导出'useEffect'" 来源https://github.com/formkit/auto-animate/issues/55 原因:AutoAnimate使用了服务器端不可用的DOM API 解决方法:使用动态导入(参考
templates/vite-ssr-safe.tsx

Issue #2: Conditional Parent Rendering

问题2:父元素条件渲染

Error: Animations don't work when parent is conditional Source: https://github.com/formkit/auto-animate/issues/8 Why It Happens: Ref can't attach to non-existent element Prevention:
tsx
// ❌ Wrong
{showList && <ul ref={parent}>...</ul>}

// ✅ Correct
<ul ref={parent}>{showList && items.map(...)}</ul>
错误现象:父元素条件渲染时动画无法生效 来源https://github.com/formkit/auto-animate/issues/8 原因:引用无法附加到不存在的元素 解决方法
tsx
// ❌ 错误写法
{showList && <ul ref={parent}>...</ul>}

// ✅ 正确写法
<ul ref={parent}>{showList && items.map(...)}</ul>

Issue #3: Missing Unique Keys

问题3:缺少唯一key

Error: Items don't animate correctly or flash Source: Official docs Why It Happens: React can't track which items changed Prevention: Always use unique, stable keys (
key={item.id}
)
错误现象:项动画异常或出现闪烁 来源:官方文档 原因:React无法追踪哪些项发生了变化 解决方法:始终使用唯一且稳定的key(
key={item.id}

Issue #4: Flexbox Width Issues

问题4:Flexbox宽度问题

Error: Elements snap to width instead of animating smoothly Source: Official docs Why It Happens:
flex-grow: 1
waits for surrounding content Prevention: Use explicit width instead of flex-grow for animated elements
错误现象:元素直接切换宽度而非平滑动画 来源:官方文档 原因
flex-grow: 1
会等待周围内容加载 解决方法:为动画元素使用明确宽度而非flex-grow

Issue #5: Table Row Display Issues

问题5:表格行显示问题

Error: Table structure breaks when removing rows Source: https://github.com/formkit/auto-animate/issues/7 Why It Happens: Display: table-row conflicts with animations Prevention: Apply to
<tbody>
instead of individual rows, or use div-based layouts
错误现象:删除行时表格结构损坏 来源https://github.com/formkit/auto-animate/issues/7 原因:display: table-row与动画冲突 解决方法:将动画应用于
<tbody>
而非单独行,或使用基于div的布局

Issue #6: Jest Testing Errors

问题6:Jest测试错误

Error: "Cannot find module '@formkit/auto-animate/react'" Source: https://github.com/formkit/auto-animate/issues/29 Why It Happens: Jest doesn't resolve ESM exports correctly Prevention: Configure
moduleNameMapper
in jest.config.js
错误信息:"找不到模块'@formkit/auto-animate/react'" 来源https://github.com/formkit/auto-animate/issues/29 原因:Jest无法正确解析ESM导出 解决方法:在jest.config.js中配置
moduleNameMapper

Issue #7: esbuild Compatibility

问题7:esbuild兼容性问题

Error: "Path '.' not exported by package" Source: https://github.com/formkit/auto-animate/issues/36 Why It Happens: ESM/CommonJS condition mismatch Prevention: Configure esbuild to handle ESM modules properly
错误信息:"路径'.'未被包导出" 来源https://github.com/formkit/auto-animate/issues/36 原因:ESM/CommonJS条件不匹配 解决方法:配置esbuild以正确处理ESM模块

Issue #8: CSS Position Side Effects

问题8:CSS定位副作用

Error: Layout breaks after adding AutoAnimate Source: Official docs Why It Happens: Parent automatically gets
position: relative
Prevention: Account for position change in CSS or set explicitly
错误现象:添加AutoAnimate后布局损坏 来源:官方文档 原因:父元素会自动设置
position: relative
解决方法:在CSS中考虑定位变化或显式设置定位

Issue #9: Vue/Nuxt Registration Errors

问题9:Vue/Nuxt注册错误

Error: "Failed to resolve directive: auto-animate" Source: https://github.com/formkit/auto-animate/issues/43 Why It Happens: Plugin not registered correctly Prevention: Proper plugin setup in Vue/Nuxt config (see references/)
错误信息:"无法解析指令:auto-animate" 来源https://github.com/formkit/auto-animate/issues/43 原因:插件未正确注册 解决方法:在Vue/Nuxt配置中正确设置插件(参考references/)

Issue #10: Angular ESM Issues

问题10:Angular ESM问题

Error: Build fails with "ESM-only package" Source: https://github.com/formkit/auto-animate/issues/72 Why It Happens: CommonJS build environment Prevention: Configure ng-packagr for Angular Package Format

错误现象:构建失败提示"仅支持ESM的包" 来源https://github.com/formkit/auto-animate/issues/72 原因:CommonJS构建环境 解决方法:配置ng-packagr以适配Angular包格式

When to Use AutoAnimate vs Motion

AutoAnimate与Motion的适用场景对比

Use AutoAnimate When:

选择AutoAnimate的场景:

  • ✅ Simple list transitions (add/remove/sort)
  • ✅ Accordion expand/collapse
  • ✅ Toast notifications fade in/out
  • ✅ Form validation messages appear/disappear
  • ✅ Zero configuration preferred
  • ✅ Small bundle size critical (3.28 KB)
  • ✅ Applying to existing/3rd-party code
  • ✅ "Good enough" animations acceptable
  • ✅ 简单列表过渡(添加/删除/排序)
  • ✅ 折叠面板展开/收起
  • ✅ 提示弹窗淡入/淡出
  • ✅ 表单验证消息显示/隐藏
  • ✅ 偏好零配置
  • ✅ 对包体积要求严格(3.28 KB)
  • ✅ 应用于现有或第三方代码
  • ✅ 可接受"足够好"的动画效果

Use Motion When:

选择Motion的场景:

  • ✅ Complex choreographed animations
  • ✅ Gesture controls (drag, swipe, hover)
  • ✅ Scroll-based animations
  • ✅ Spring physics animations
  • ✅ SVG path animations
  • ✅ Keyframe control needed
  • ✅ Animation variants/orchestration
  • ✅ Custom easing curves
Rule of Thumb: Use AutoAnimate for 90% of cases, Motion for hero/interactive animations.

  • ✅ 复杂编排动画
  • ✅ 手势控制(拖拽、滑动、悬停)
  • ✅ 基于滚动的动画
  • ✅ 弹簧物理动画
  • ✅ SVG路径动画
  • ✅ 需要关键帧控制
  • ✅ 动画变体/编排
  • ✅ 自定义缓动曲线
经验法则:90%的场景使用AutoAnimate,核心交互/英雄动画使用Motion。

Critical Rules

关键规则

Always Do

必须遵守

Use unique, stable keys -
key={item.id}
not
key={index}
Keep parent in DOM - Parent ref element always rendered ✅ Client-only for SSR - Dynamic import for server environments ✅ Respect accessibility - Keep
disrespectUserMotionPreference: false
Test with motion disabled - Verify UI works without animations ✅ Use explicit width - Avoid flex-grow on animated elements ✅ Apply to tbody for tables - Not individual rows
使用唯一且稳定的key - 使用
key={item.id}
而非
key={index}
保持父元素在DOM中 - 父元素引用必须始终渲染 ✅ SSR环境仅客户端导入 - 服务器环境使用动态导入 ✅ 尊重无障碍要求 - 保持
disrespectUserMotionPreference: false
禁用动画时测试 - 验证无动画时UI仍可正常工作 ✅ 使用明确宽度 - 避免为动画元素使用flex-grow ✅ 表格动画应用于tbody - 而非单独行

Never Do

禁止操作

Conditional parent -
{show && <ul ref={parent}>}
Index as key -
key={index}
breaks animations ❌ Ignore SSR - Will break in Cloudflare Workers/Next.js ❌ Force animations -
disrespectUserMotionPreference: true
breaks accessibility ❌ Animate tables directly - Use tbody or div-based layout ❌ Skip unique keys - Required for proper animation ❌ Complex animations - Use Motion instead

父元素条件渲染 -
{show && <ul ref={parent}>}
使用索引作为key -
key={index}
会破坏动画 ❌ 忽略SSR环境 - 在Cloudflare Workers/Next.js中会报错 ❌ 强制动画 -
disrespectUserMotionPreference: true
会违反无障碍要求 ❌ 直接动画表格行 - 使用tbody或基于div的布局 ❌ 跳过唯一key - 正确动画必须使用唯一key ❌ 复杂动画场景 - 改用Motion

Configuration

配置说明

AutoAnimate is zero-config by default. Optional customization:
tsx
import { useAutoAnimate } from "@formkit/auto-animate/react";

const [parent] = useAutoAnimate({
  duration: 250, // milliseconds (default: 250)
  easing: "ease-in-out", // CSS easing (default: "ease-in-out")
  // disrespectUserMotionPreference: false, // Keep false!
});
Recommendation: Use defaults unless you have specific design requirements.

AutoAnimate默认零配置,可选自定义设置:
tsx
import { useAutoAnimate } from "@formkit/auto-animate/react";

const [parent] = useAutoAnimate({
  duration: 250, // milliseconds (default: 250)
  easing: "ease-in-out", // CSS easing (default: "ease-in-out")
  // disrespectUserMotionPreference: false, // Keep false!
});
建议:除非有特定设计需求,否则使用默认配置。

Using Bundled Resources

捆绑资源使用

Templates (templates/)

模板(templates/)

Copy-paste ready examples:
  • react-basic.tsx
    - Simple list with add/remove/shuffle
  • react-typescript.tsx
    - Typed setup with custom config
  • filter-sort-list.tsx
    - Animated filtering and sorting
  • accordion.tsx
    - Expandable sections
  • toast-notifications.tsx
    - Fade in/out messages
  • form-validation.tsx
    - Error messages animation
  • vite-ssr-safe.tsx
    - Cloudflare Workers/SSR pattern
可直接复制使用的示例:
  • react-basic.tsx
    - 包含添加/删除/随机排序的简单列表
  • react-typescript.tsx
    - 带自定义配置的类型化设置
  • filter-sort-list.tsx
    - 带动画的过滤和排序列表
  • accordion.tsx
    - 可展开的折叠面板
  • toast-notifications.tsx
    - 淡入淡出的提示消息
  • form-validation.tsx
    - 表单错误消息动画
  • vite-ssr-safe.tsx
    - Cloudflare Workers/SSR适配方案

References (references/)

参考文档(references/)

  • auto-animate-vs-motion.md
    - Decision guide for which to use
  • css-conflicts.md
    - Flexbox, table, and position gotchas
  • ssr-patterns.md
    - Next.js, Nuxt, Workers workarounds
  • auto-animate-vs-motion.md
    - 库选择决策指南
  • css-conflicts.md
    - Flexbox、表格和定位常见问题
  • ssr-patterns.md
    - Next.js、Nuxt、Workers适配方案

Scripts (scripts/)

脚本(scripts/)

  • init-auto-animate.sh
    - Automated setup script

  • init-auto-animate.sh
    - 自动化安装脚本

Cloudflare Workers Compatibility

Cloudflare Workers兼容性

AutoAnimate works perfectly with Cloudflare Workers Static Assets:
Client-side only - Runs in browser, not Worker runtime ✅ No Node.js deps - Pure browser code ✅ Edge-friendly - 3.28 KB gzipped ✅ SSR-safe - Use dynamic imports (see templates/)
Vite Config:
typescript
export default defineConfig({
  plugins: [react(), cloudflare()],
  ssr: {
    external: ["@formkit/auto-animate"],
  },
});

AutoAnimate可完美适配Cloudflare Workers静态资源:
仅客户端运行 - 在浏览器中运行,而非Worker runtime ✅ 无Node.js依赖 - 纯浏览器代码 ✅ 边缘友好 - 3.28 KB压缩后体积 ✅ SSR安全 - 使用动态导入(参考templates/)
Vite配置
typescript
export default defineConfig({
  plugins: [react(), cloudflare()],
  ssr: {
    external: ["@formkit/auto-animate"],
  },
});

Accessibility

无障碍支持

AutoAnimate respects
prefers-reduced-motion
automatically:
css
/* User's system preference */
@media (prefers-reduced-motion: reduce) {
  /* AutoAnimate disables animations automatically */
}
Critical: Never set
disrespectUserMotionPreference: true
- this breaks accessibility.

AutoAnimate会自动遵循
prefers-reduced-motion
设置:
css
/* User's system preference */
@media (prefers-reduced-motion: reduce) {
  /* AutoAnimate disables animations automatically */
}
关键提示:切勿设置
disrespectUserMotionPreference: true
- 这会违反无障碍要求。

Official Documentation

官方文档

Package Versions (Verified 2025-11-07)

已验证的包版本(2025-11-07)

json
{
  "dependencies": {
    "@formkit/auto-animate": "^0.9.0"
  },
  "devDependencies": {
    "react": "^19.2.0",
    "vite": "^6.0.0"
  }
}

json
{
  "dependencies": {
    "@formkit/auto-animate": "^0.9.0"
  },
  "devDependencies": {
    "react": "^19.2.0",
    "vite": "^6.0.0"
  }
}

Production Example

生产环境示例

This skill is based on production testing:
  • Bundle Size: 3.28 KB gzipped
  • Setup Time: 2 minutes (vs 15 min with Motion)
  • Errors: 0 (all 10 known issues prevented)
  • Validation: ✅ Works with Vite, Tailwind v4, Cloudflare Workers, React 19
Tested Scenarios:
  • ✅ Filter/sort lists
  • ✅ Accordion components
  • ✅ Toast notifications
  • ✅ Form validation messages
  • ✅ SSR/Cloudflare Workers
  • ✅ Accessibility (prefers-reduced-motion)

本指南基于生产环境测试:
  • 包体积:3.28 KB压缩后
  • 搭建时间:2分钟(对比Motion的15分钟)
  • 错误数:0(已预防所有10个已知问题)
  • 验证环境:✅ 支持Vite、Tailwind v4、Cloudflare Workers、React 19
测试场景:
  • ✅ 过滤/排序列表
  • ✅ 折叠面板组件
  • ✅ 提示弹窗
  • ✅ 表单验证消息
  • ✅ SSR/Cloudflare Workers
  • ✅ 无障碍支持(prefers-reduced-motion)

Troubleshooting

故障排查

Problem: Animations not working

问题:动画无法生效

Solution: Check these common issues:
  1. Is parent element always in DOM? (not conditional)
  2. Do items have unique, stable keys?
  3. Is ref attached to immediate parent of animated children?
解决方法:检查以下常见问题:
  1. 父元素是否始终在DOM中?(不能是条件渲染)
  2. 项是否有唯一且稳定的key?
  3. 引用是否附加到动画子元素的直接父元素?

Problem: SSR/Next.js errors

问题:SSR/Next.js错误

Solution: Use dynamic import:
tsx
useEffect(() => {
  if (typeof window !== "undefined") {
    import("@formkit/auto-animate").then(({ default: autoAnimate }) => {
      autoAnimate(parent);
    });
  }
}, [parent]);
解决方法:使用动态导入:
tsx
useEffect(() => {
  if (typeof window !== "undefined") {
    import("@formkit/auto-animate").then(({ default: autoAnimate }) => {
      autoAnimate(parent);
    });
  }
}, [parent]);

Problem: Items flash instead of animating

问题:项闪烁而非动画

Solution: Add unique keys:
key={item.id}
not
key={index}
解决方法:添加唯一key:使用
key={item.id}
而非
key={index}

Problem: Flexbox width issues

问题:Flexbox宽度异常

Solution: Use explicit width instead of
flex-grow: 1
解决方法:使用明确宽度而非
flex-grow: 1

Problem: Table rows don't animate

问题:表格行无法动画

Solution: Apply ref to
<tbody>
, not individual
<tr>
elements

解决方法:将引用应用于
<tbody>
而非单独的
<tr>
元素

Complete Setup Checklist

完整搭建检查清单

  • Installed
    @formkit/auto-animate@0.9.0
  • Using React 19+ (or Vue/Svelte)
  • Added ref to parent element
  • Parent element always rendered (not conditional)
  • List items have unique, stable keys
  • Tested with
    prefers-reduced-motion
  • SSR-safe if using Cloudflare Workers/Next.js
  • No flexbox width issues
  • Dev server runs without errors
  • Production build succeeds

Questions? Issues?
  1. Check
    templates/
    for working examples
  2. Check
    references/auto-animate-vs-motion.md
    for library comparison
  3. Check
    references/ssr-patterns.md
    for SSR workarounds
  4. Check official docs: https://auto-animate.formkit.com
  5. Check GitHub issues: https://github.com/formkit/auto-animate/issues

Production Ready? ✅ Yes - 13.6k stars, actively maintained, zero dependencies.
  • 已安装
    @formkit/auto-animate@0.9.0
  • 使用React 19+(或Vue/Svelte)
  • 已为父元素添加引用
  • 父元素始终渲染(非条件渲染)
  • 列表项有唯一且稳定的key
  • 已测试
    prefers-reduced-motion
    场景
  • 若使用Cloudflare Workers/Next.js,已确保SSR安全
  • 无Flexbox宽度问题
  • 开发服务器运行无错误
  • 生产构建成功

有疑问或遇到问题?
  1. 查看
    templates/
    中的可用示例
  2. 查看
    references/auto-animate-vs-motion.md
    进行库对比
  3. 查看
    references/ssr-patterns.md
    获取SSR适配方案
  4. 查看官方文档:https://auto-animate.formkit.com
  5. 查看GitHub issues:https://github.com/formkit/auto-animate/issues

是否可用于生产环境? ✅ 是 - 拥有13.6k星标,持续维护,无依赖项。