# Text Loop

> Cycles through an array of children with smooth enter and exit transitions, swapping content on a configurable interval.

Docs: https://ui.cnippet.dev/motion/text-animations/text-loop

```tsx
import { TextLoop } from "@/registry/default/motion/text-loop";

export default function TextLoopHeading() {
  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <h1 className="text-center font-bold text-4xl text-foreground tracking-tight sm:text-5xl">
        Components that are{" "}
        <TextLoop
          className="text-primary"
          interval={2.5}
          transition={{ duration: 0.4, ease: "easeInOut" }}
        >
          <span>beautiful</span>
          <span>accessible</span>
          <span>composable</span>
          <span>fast</span>
        </TextLoop>
      </h1>
    </div>
  );
}
```

## Installation

**CLI**

```bash
npx shadcn@latest add @cnippet/text-loop
```

**Manual**

1. Install the following dependencies:

```bash
npm install motion
```

2. Copy and paste the following code into your project.

`components/motion/text-loop.tsx`

```tsx
"use client";

import {
  AnimatePresence,
  type AnimatePresenceProps,
  motion,
  type Transition,
  useReducedMotion,
  type Variants,
} from "motion/react";
import { Children, useEffect, useState } from "react";
import { cn } from "@/lib/utils";

export type TextLoopProps = {
  children: React.ReactNode[];
  className?: string;
  interval?: number;
  transition?: Transition;
  variants?: Variants;
  onIndexChange?: (index: number) => void;
  trigger?: boolean;
  mode?: AnimatePresenceProps["mode"];
};

const defaultVariants: Variants = {
  animate: { opacity: 1, y: 0 },
  exit: { opacity: 0, y: -20 },
  initial: { opacity: 0, y: 20 },
};

export function TextLoop({
  children,
  className,
  interval = 2,
  transition = { duration: 0.3 },
  variants,
  onIndexChange,
  trigger = true,
  mode = "popLayout",
}: TextLoopProps) {
  const reduceMotion = useReducedMotion();
  const [currentIndex, setCurrentIndex] = useState(0);
  const items = Children.toArray(children);

  useEffect(() => {
    if (!trigger) return;
    const timer = setInterval(() => {
      setCurrentIndex((current) => {
        const next = (current + 1) % items.length;
        onIndexChange?.(next);
        return next;
      });
    }, interval * 1000);
    return () => clearInterval(timer);
  }, [items.length, interval, onIndexChange, trigger]);

  return (
    <div className={cn("relative inline-block whitespace-nowrap", className)}>
      <AnimatePresence initial={false} mode={mode}>
        <motion.div
          animate="animate"
          exit="exit"
          initial="initial"
          key={currentIndex}
          transition={reduceMotion ? { duration: 0 } : transition}
          variants={variants ?? defaultVariants}
        >
          {items[currentIndex]}
        </motion.div>
      </AnimatePresence>
    </div>
  );
}
```

3. Update the import paths to match your project setup.

## Usage

```tsx
import { TextLoop } from "@/components/motion/text-loop";
```

```tsx
<TextLoop interval={2}>
  <span>First</span>
  <span>Second</span>
  <span>Third</span>
</TextLoop>
```

## Anatomy

```tsx
<TextLoop interval={2}> {/* shows one child at a time */}
  <span>First</span>
  <span>Second</span>
</TextLoop>
```

## Good to know

- Each child is one item. Unlike `RotatingText`, the items can be any elements, not just strings.
- `interval` is in seconds (default `2`). `trigger={false}` pauses the loop.
- `onIndexChange` reports which item is showing.
- Screen readers only hear the item that's showing when they reach it.
- When the user has turned on reduced motion, items still change on the interval but swap instantly, with no transition.

## Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `children` | `ReactNode[]` | — | Array of items to loop through |
| `interval` | `number` | `2` | Seconds between transitions |
| `transition` | `Transition` | `{ duration: 0.3 }` | Motion transition for enter/exit |
| `variants` | `Variants` | fade + slide-y | Custom enter/exit variants |
| `mode` | `AnimatePresenceProps["mode"]` | `"popLayout"` | AnimatePresence mode |
| `trigger` | `boolean` | `true` | Set `false` to pause the loop |
| `onIndexChange` | `(index: number) => void` | — | Callback fired on each step |
| `className` | `string` | — | Class applied to the container |

## Examples

### Looping Adjectives

Inline within a heading, cycling benefit words in the brand color. Each child is a `<span>` but can be any ReactNode.

```tsx
import { TextLoop } from "@/registry/default/motion/text-loop";

export default function TextLoopHeading() {
  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <h1 className="text-center font-bold text-4xl text-foreground tracking-tight sm:text-5xl">
        Components that are{" "}
        <TextLoop
          className="text-primary"
          interval={2.5}
          transition={{ duration: 0.4, ease: "easeInOut" }}
        >
          <span>beautiful</span>
          <span>accessible</span>
          <span>composable</span>
          <span>fast</span>
        </TextLoop>
      </h1>
    </div>
  );
}
```

### Animated Status Badge

Rich content items — icon + label — cycle inside a pill badge with a vertical slide transition. The `variants` prop drives direction.

```tsx
import { TextLoop } from "@/registry/default/motion/text-loop";

const statuses = [
  { color: "bg-emerald-500", label: "All systems operational" },
  { color: "bg-blue-500", label: "Deploying v2.4.1" },
  { color: "bg-amber-500", label: "Elevated latency" },
];

export default function TextLoopStatus() {
  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <div className="flex items-center gap-2 rounded-full border border-border bg-card px-4 py-2 shadow-sm">
        <TextLoop
          interval={3}
          transition={{ duration: 0.35 }}
          variants={{
            animate: { opacity: 1, y: 0 },
            exit: { opacity: 0, y: -8 },
            initial: { opacity: 0, y: 8 },
          }}
        >
          {statuses.map(({ color, label }) => (
            <span className="flex items-center gap-2" key={label}>
              <span className={`h-2 w-2 rounded-full ${color}`} />
              <span className="font-medium text-foreground text-sm">
                {label}
              </span>
            </span>
          ))}
        </TextLoop>
      </div>
    </div>
  );
}
```

### Horizontal Slide

Custom `variants` swap the default fade+y for a horizontal slide, matching the direction to a left-to-right reading flow.

```tsx
import { TextLoop } from "@/registry/default/motion/text-loop";

export default function TextLoopSlide() {
  return (
    <div className="flex min-h-50 flex-col items-center justify-center gap-4 px-6">
      <div className="flex items-baseline gap-2 font-bold text-4xl text-foreground tracking-tight sm:text-5xl">
        <span>Made for</span>
        <TextLoop
          className="overflow-hidden"
          interval={2}
          transition={{ duration: 0.5, ease: [0.25, 0.1, 0.25, 1] }}
          variants={{
            animate: { opacity: 1, x: 0 },
            exit: { opacity: 0, x: 40 },
            initial: { opacity: 0, x: -40 },
          }}
        >
          <span className="text-violet-500">founders</span>
          <span className="text-blue-500">designers</span>
          <span className="text-emerald-500">developers</span>
        </TextLoop>
      </div>
      <p className="max-w-sm text-center text-base text-muted-foreground">
        Production-ready animated components you can drop into any project.
      </p>
    </div>
  );
}
```
