# Scroll Swap Text

> Text slides in from below as its scrollable container is navigated — the current copy exits upward while a clone rises into place, creating a smooth reveal tied directly to scroll position.

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

```tsx
"use client";
import { useRef } from "react";
import { ScrollSwapText } from "@/registry/default/motion/scroll-swap-text";

const features = [
  "Zero-config setup",
  "Spring physics built-in",
  "Accessible by default",
  "TypeScript first",
  "Tree-shakeable exports",
  "Server component ready",
];

export default function ScrollSwapTextFeatureList() {
  const containerRef = useRef<HTMLDivElement>(null);

  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <div
        className="h-48 w-full max-w-sm overflow-y-scroll rounded-lg border border-border"
        ref={containerRef}
      >
        {features.map((feature) => (
          <ScrollSwapText
            as="div"
            className="border-border border-b px-5 py-4 font-medium text-base last:border-0"
            containerRef={containerRef}
            key={feature}
          >
            {feature}
          </ScrollSwapText>
        ))}
      </div>
    </div>
  );
}
```

## Installation

**CLI**

```bash
npx shadcn@latest add @cnippet/scroll-swap-text
```

**Manual**

1. Install the following dependencies:

```bash
npm install motion
```

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

`components/motion/scroll-swap-text.tsx`

```tsx
//biome-ignore-all lint/suspicious/noExplicitAny: motion offset type requires any cast
"use client";

import {
  motion,
  useReducedMotion,
  useScroll,
  useSpring,
  useTransform,
} from "motion/react";
import React, { type ElementType, useMemo, useRef } from "react";
import { cn } from "@/lib/utils";

function extractText(children: React.ReactNode): string {
  if (children == null) return "";
  if (typeof children === "string") return children;
  if (typeof children === "number") return String(children);
  if (Array.isArray(children)) return children.map(extractText).join("");
  if (React.isValidElement(children)) {
    const props = (children as React.ReactElement).props;
    return extractText((props as { children?: React.ReactNode }).children);
  }
  return "";
}

export type ScrollSwapTextProps = {
  children: React.ReactNode;
  as?: ElementType;
  containerRef: React.RefObject<HTMLElement | null>;
  offset?: [string, string];
  className?: string;
  springConfig?: { stiffness?: number; damping?: number; mass?: number };
};

export function ScrollSwapText({
  children,
  as = "span",
  offset = ["0 0", "0 1"],
  className,
  containerRef,
  springConfig = { damping: 30, stiffness: 200 },
  ...props
}: ScrollSwapTextProps) {
  const reduceMotion = useReducedMotion();
  const ref = useRef<HTMLElement>(null);

  const text = useMemo(() => {
    try {
      return extractText(children);
    } catch {
      return "";
    }
  }, [children]);

  const { scrollYProgress } = useScroll({
    container: containerRef,
    offset: offset as any,
    target: ref,
  });

  const springProgress = useSpring(scrollYProgress, springConfig);
  // Reduced motion: track scroll directly, without the spring's overshoot.
  const progress = reduceMotion ? scrollYProgress : springProgress;
  const top = useTransform(progress, [0, 1], ["0%", "-100%"]);
  const bottom = useTransform(progress, [0, 1], ["100%", "0%"]);

  const ElementTag = as;

  return (
    <ElementTag
      className={cn(
        "relative flex items-center justify-center overflow-hidden p-0",
        className,
      )}
      ref={ref}
      {...props}
    >
      <span aria-hidden="true" className="relative text-transparent">
        {text}
      </span>
      <motion.span className="absolute" style={{ top }}>
        {text}
      </motion.span>
      <motion.span
        aria-hidden="true"
        className="absolute"
        style={{ top: bottom }}
      >
        {text}
      </motion.span>
    </ElementTag>
  );
}
```

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

## Usage

```tsx
import { ScrollSwapText } from "@/components/motion/scroll-swap-text";
```

```tsx
const containerRef = useRef<HTMLDivElement>(null);

<div ref={containerRef} className="h-64 overflow-y-scroll">
  <ScrollSwapText containerRef={containerRef}>
    Scrollable text item
  </ScrollSwapText>
</div>
```

## Anatomy

```tsx
<div ref={containerRef} className="h-64 overflow-y-scroll"> {/* the element that scrolls */}
  <ScrollSwapText containerRef={containerRef}>Scrollable text</ScrollSwapText> {/* text that swaps with scroll */}
</div>
```

## Good to know

- `containerRef` is required. Pass a ref to the element that scrolls, not to the page.
- `children` should be plain text.
- `offset` sets which part of the scroll range drives the swap (Motion `useScroll` offsets).
- When the user has turned on reduced motion, the swap follows the scroll position directly, without the spring.

## Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `children` | `React.ReactNode` | — | Text content to display and animate |
| `as` | `ElementType` | `"span"` | HTML element rendered as the container |
| `containerRef` | `RefObject<HTMLElement>` | — | **Required.** Ref to the scrollable container that drives the animation |
| `offset` | `[string, string]` | `["0 0", "0 1"]` | Scroll offset range passed to Motion's `useScroll` |
| `springConfig` | `{ stiffness?, damping?, mass? }` | `{ stiffness: 200, damping: 30 }` | Spring configuration for the scroll animation |
| `className` | `string` | — | Class on the outer element |

## Examples

### Feature List

A scrollable feature list where each item slides in as you scroll. Pass the same `containerRef` to every `ScrollSwapText` so they all track the same scroll container.

```tsx
"use client";
import { useRef } from "react";
import { ScrollSwapText } from "@/registry/default/motion/scroll-swap-text";

const features = [
  "Zero-config setup",
  "Spring physics built-in",
  "Accessible by default",
  "TypeScript first",
  "Tree-shakeable exports",
  "Server component ready",
];

export default function ScrollSwapTextFeatureList() {
  const containerRef = useRef<HTMLDivElement>(null);

  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <div
        className="h-48 w-full max-w-sm overflow-y-scroll rounded-lg border border-border"
        ref={containerRef}
      >
        {features.map((feature) => (
          <ScrollSwapText
            as="div"
            className="border-border border-b px-5 py-4 font-medium text-base last:border-0"
            containerRef={containerRef}
            key={feature}
          >
            {feature}
          </ScrollSwapText>
        ))}
      </div>
    </div>
  );
}
```

### Step-by-Step Process

Numbered steps in a compact scroll container — each label swaps in as it crosses the scroll threshold.

```tsx
"use client";
import { useRef } from "react";
import { ScrollSwapText } from "@/registry/default/motion/scroll-swap-text";

const steps = [
  { label: "Install the package", num: "01" },
  { label: "Add the component", num: "02" },
  { label: "Configure your theme", num: "03" },
  { label: "Deploy to production", num: "04" },
  { label: "Measure the impact", num: "05" },
  { label: "Iterate and improve", num: "06" },
];

export default function ScrollSwapTextSteps() {
  const containerRef = useRef<HTMLDivElement>(null);

  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <div
        className="h-48 w-full max-w-sm overflow-y-scroll"
        ref={containerRef}
      >
        {steps.map((step) => (
          <div
            className="flex items-center gap-4 border-border border-b py-5 last:border-0"
            key={step.num}
          >
            <span className="w-8 shrink-0 font-mono text-muted-foreground text-sm">
              {step.num}
            </span>
            <ScrollSwapText
              className="font-medium text-base"
              containerRef={containerRef}
            >
              {step.label}
            </ScrollSwapText>
          </div>
        ))}
      </div>
    </div>
  );
}
```

### Testimonial Quotes

Pull quotes scroll into view one at a time. The consistent swap motion creates a unified rhythm across all items.

```tsx
"use client";
import { useRef } from "react";
import { ScrollSwapText } from "@/registry/default/motion/scroll-swap-text";

const quotes = [
  { author: "Sarah K.", text: "The animation quality is exceptional." },
  { author: "Marco R.", text: "Saved us weeks of development time." },
  { author: "Priya M.", text: "Our conversion rate jumped 30%." },
  { author: "Tom B.", text: "Best component library we have used." },
  { author: "Yuki T.", text: "The docs are incredibly clear." },
];

export default function ScrollSwapTextTestimonials() {
  const containerRef = useRef<HTMLDivElement>(null);

  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <div
        className="h-48 w-full max-w-sm overflow-y-scroll"
        ref={containerRef}
      >
        {quotes.map((q, i) => (
          <div
            className="border-border border-b px-1 py-5 last:border-0"
            key={i}
          >
            <ScrollSwapText
              as="p"
              className="text-base text-foreground italic"
              containerRef={containerRef}
            >
              {`"${q.text}"`}
            </ScrollSwapText>
            <p className="mt-1 text-muted-foreground text-sm">{q.author}</p>
          </div>
        ))}
      </div>
    </div>
  );
}
```
