К основному содержанию
скилл CX Codex

auto-animate — скилл для Claude Code: что делает и как установить

Скилл показывает, как подключить @formkit/auto-animate в React для списков, аккордеонов и toast-уведомлений — анимация без конфигов, 3.28 КБ.

MIT 257 установок ★ 250 обновлён 2026-10-20

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add secondsky/claude-skills --skill auto-animate -a claude-code
Открыть на GitHub

Что делает auto-animate

Когда добавляешь или удаляешь элементы в списке, AutoAnimate плавно их двигает. Подключение — одна строка: импорт хука useAutoAnimate, привязка рефа к родителю и готово. Обязательны стабильные ключи у элементов (key={item.id}), родитель всегда в DOM — условное отображение ломает анимацию.

Скилл содержит решения десяти частых проблем: ошибки импорта в Next.js и Cloudflare Workers (нужен динамический импорт на клиенте), конфликты с display: table-row (применять к <tbody>, а не к строкам), баги с flex-grow (брать явную ширину). Респектит prefers-reduced-motion из коробки.

В исходнике примеры для Vite, SSR, Jest, esbuild, таблицы сравнения с Motion и правила, когда AutoAnimate хватает, а когда нужна полноценная библиотека жестов и хореографии.

Какие задачи решает

  • анимировать список при добавлении или удалении элементов
  • починить SSR-ошибки AutoAnimate в Next.js
  • применить анимацию к аккордеону или toast без настройки
  • убрать мерцание элементов при сортировке
  • заменить Motion на лёгкую библиотеку анимаций

Примеры запросов агенту

  • Подключи @formkit/auto-animate к списку задач, чтобы элементы плавно появлялись и исчезали
  • Исправь ошибку импорта AutoAnimate в Next.js — используй динамический импорт на клиенте
  • Покажи, как применить AutoAnimate к таблице без конфликта с display: table-row

Как установить auto-animate

1Через Skills CLI (Vercel)

npx skills add secondsky/claude-skills --skill auto-animate -a claude-code

2Вручную: положить файлы

~/.claude/skills/auto-animate/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/auto-animate/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы об auto-animate

Как установить auto-animate в Claude Code?

Выполни npx skills add secondsky/claude-skills --skill auto-animate -a claude-code, скилл окажется в ~/.claude/skills/auto-animate/SKILL.md.

Что делает auto-animate?

Скилл учит подключать библиотеку @formkit/auto-animate для автоматической анимации списков, аккордеонов и уведомлений в React. Решает проблемы с SSR, конфликтами display и отсутствием ключей.

Почему AutoAnimate не работает в Next.js?

Библиотека использует DOM API, недоступные на сервере. Скилл предлагает обёртку с динамическим импортом на клиенте, чтобы избежать ошибки импорта при рендере на сервере.

Исходный текст

SKILL.md · MIT
---
name: auto-animate
description: "AutoAnimate (@formkit/auto-animate) zero-config animations for React. Use for list transitions, accordions, toasts, or encountering SSR errors, animation libraries complexity."

metadata:
  keywords:
    - auto-animate
    - "@formkit/auto-animate"
    - formkit
    - zero-config animation
    - automatic animations
    - drop-in animation
    - list animations
    - accordion animation
    - toast animation
    - form validation animation
    - lightweight animation
    - 2kb animation
    - prefers-reduced-motion
    - accessible animations
    - vite react animation
    - cloudflare workers animation
    - ssr safe animation

license: MIT
---
# AutoAnimate

**Status**: Production Ready ✅
**Last Updated**: 2026-08-03
**Dependencies**: None (works with any React setup)
**Latest Versions**: @formkit/[email protected]

---

## Quick Start (2 Minutes)

### 1. Install 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)

### 2. Add to Your Component

```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

### 3. Use in Production (SSR-Safe)

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;
}
```

---

## Known Issues Prevention

This skill prevents **10+** documented issues:

### Issue #1: SSR/Next.js Import Errors
**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`)

### Issue #2: Conditional Parent Rendering
**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>
```

### Issue #3: Missing Unique Keys
**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}`)

### Issue #4: Flexbox Width Issues
**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

### Issue #5: Table Row Display Issues
**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

### Issue #6: Jest Testing Errors
**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

### Issue #7: esbuild Compatibility
**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

### Issue #8: CSS Position Side Effects
**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

### Issue #9: Vue/Nuxt Registration Errors
**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/)

### Issue #10: Angular ESM Issues
**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

---

## When to Use AutoAnimate vs Motion

### Use AutoAnimate When:
- ✅ 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

### Use Motion When:
- ✅ 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.

---

## 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

### 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

---

## 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.

---

## Using Bundled Resources

### 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

### 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

### Scripts (scripts/)

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

---

## Cloudflare Workers Compatibility

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"],
  },
});
```

---

## 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.

---

## Official Documentation

- **Official Site**: https://auto-animate.formkit.com
- **GitHub**: https://github.com/formkit/auto-animate
- **npm**: https://www.npmjs.com/package/@formkit/auto-animate
- **React Docs**: https://auto-animate.formkit.com/react
- **Video Tutorial**: Laracasts video (see README)

---

## Package Versions (Verified 2026-08-03)

```json
{
  "dependencies": {
    "@formkit/auto-animate": "^0.10.0"
  },
  "devDependencies": {
    "react": "^19.2.0",
    "vite": "^7.3.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)

---

## 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?

### Problem: SSR/Next.js errors
**Solution**: Use dynamic import:
```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}`

### Problem: Flexbox width issues
**Solution**: Use explicit width instead of `flex-grow: 1`

### Problem: Table rows don't animate
**Solution**: Apply ref to `<tbody>`, not individual `<tr>` elements

---

## Complete Setup Checklist

- [ ] Installed `@formkit/[email protected]`
- [ ] 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.

© secondsky · MIT · secondsky/claude-skills

Похожие скиллы

Все скиллы по теме «Фронтенд и UI» →
animate delphi-ai Скилл animate для Claude Code собирает правила и готовые сниппеты анимаций для React и Next.js. Помогает настраивать производительные переходы и диалоговые окна. CX Codex +1 4 000установок framer-motion-react C-Jeril Скилл framer-motion-react по Framer Motion для React и Next.js: AnimatePresence, layout-анимации, useAnimation и обход проблем с SSR. CX Codex +1 930установок animate-ui imskyleen Скилл animate-ui для Claude Code добавляет анимации в React- и Vue-компоненты. Запускается при запросах на создание «живого» интерфейса, настройку переходов или поведения элементов. CX Codex +1 1 000установок mastering-animate-presence raphael-salaja Скилл mastering-animate-presence проверяет код Motion и Framer Motion на ошибки в AnimatePresence и exit-анимациях. Пригодится при ревью модалок и списков. CX Codex +1 323установок animate-css-skill podo Скилл animate-css-skill для Claude Code добавляет анимации Animate.css в HTML, React/JSX и шаблоны WordPress на PHP. Запускается по запросам про Animate.css и CSS-анимации. CX Codex +1 209установок next vercel-labs Превращает JSON-спецификации в приложения Next.js с маршрутами, страницами и серверным рендерингом. Включается при работе с @json-render/next и генерации многостраничных приложений из JSON. CX Codex +1 8 600установок

Из того же набора138

Весь набор →
nextjs Скилл для работы с Next.js 16, React 19.2 и современными паттернами серверных компонентов, Server Actions и кэширования. Помогает при миграции с версии 15, ошибках async params и настройке Partial Prerendering. CX Codex +1 299установок feature-dev Скилл feature-dev для Claude Code ведёт разработку функции через семь фаз — от изучения кодовой базы до проверки результата. Охватывает многофайловые задачи и спорные архитектурные решения. CX Codex +1 294установок cloudflare-nextjs Скилл cloudflare-nextjs для Claude Code настраивает и развёртывает Next.js на Cloudflare Workers через OpenNext. Помогает переносить проект и разбирать ошибки среды Workers. CX Codex +1 267установок cloudflare-turnstile Скилл cloudflare-turnstile для Claude Code помогает добавить Turnstile и проверять токены на сервере. Подключается при настройке защиты форм или разборе ошибок виджета. CX Codex +1 261установок base-ui-react Скилл base-ui-react помогает собирать интерфейсы на MUI Base UI: настраивать доступные компоненты и плавающие элементы, а также переносить проект с Radix UI. CX Codex +1 259установок hono-routing Скилл hono-routing для работы с Hono: маршруты, middleware, валидация через Zod или Valibot, RPC-клиент с выводом типов. Помогает избежать 12 типичных ошибок при построении API. CX Codex +1 256установок pinia-colada Скилл pinia-colada для управления асинхронным состоянием в Vue и Nuxt через useQuery и useMutation. Помогает при кешировании, SSR, инвалидации кеша и миграции с TanStack Vue Query. CX Codex +1 253установок github-project-automation Скилл github-project-automation для Claude Code помогает настроить GitHub Actions, шаблоны задач и проверку безопасности репозитория. Также помогает искать ошибки в YAML и workflow. CX Codex +1 1установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой