Skip to main content

Char Spring Morph

A number/text readout where only the characters that actually change animate: stable place-value keys keep the steady glyphs pinned while the differing ones roll in with a staggered spring — blur, scale, and a slide whose direction is inferred from whether the value grew or shrank. Layout animation reflows the rest.

TextReactMotionTailwind CSS
CSSTailwind

Manual

Create a file and paste the following code into it.

char-spring-morph.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
"use client";

import { useEffect, useLayoutEffect, useMemo, useRef } from "react";
import { motion, useSpring, useTransform } from "motion/react";
import { cn } from "@/lib/cn";

/* ------------------------------------------------------------------ */
/*  CharSpringMorph                                                   */
/* ------------------------------------------------------------------ */

interface Token {
  key: string;
  char: string;
  isAnimatable: boolean;
}

/** Stable per-character keys so only the glyphs that actually change animate.
 *  Digits key by their place (right to left) so "9→10" rolls the ones column;
 *  letters key by index; symbols key by running count. */
function tokenize(value: string): Token[] {
  let digitPlace = 0;
  const symbolCount = new Map<string, number>();
  return value
    .split("")
    .map((char, index) => ({
      char,
      index,
      isDigit: /\d/.test(char),
      isLetter: /\p{L}/u.test(char),
    }))
    .reverse()
    .map(({ char, index, isDigit, isLetter }) => {
      if (isDigit) {
        const key = `digit-${digitPlace}`;
        digitPlace += 1;
        return { key, char, isAnimatable: true };
      }
      if (isLetter) return { key: `letter-${index}`, char, isAnimatable: true };
      const seen = symbolCount.get(char) ?? 0;
      symbolCount.set(char, seen + 1);
      return { key: `symbol-${char}-${seen}`, char, isAnimatable: false };
    })
    .reverse();
}

function numericValue(value: string): number | undefined {
  const n = Number(value.replace(/[^0-9.-]/g, ""));
  return Number.isFinite(n) ? n : undefined;
}

interface CharProps {
  char: string;
  isAnimatable: boolean;
  animateOnMount: boolean;
  animationKey: string;
  enterDirection: "up" | "down";
  animationDelay: number;
  className?: string;
  enterStiffness?: number;
  enterDamping?: number;
  enterY?: number;
  enterBlur?: number;
  enterScale?: number;
  layoutAnimation?: boolean;
}

function Char({
  char,
  isAnimatable,
  animateOnMount,
  animationKey,
  enterDirection,
  animationDelay,
  className,
  enterStiffness = 170,
  enterDamping = 10,
  enterY = 32,
  enterBlur = 52,
  enterScale = 0.7,
  layoutAnimation = true,
}: CharProps) {
  const prevChar = useRef(char);
  const prevKey = useRef(animationKey);
  const isFirst = useRef(true);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);

  const config = { stiffness: enterStiffness, damping: enterDamping };
  const y = useSpring(0, config);
  const opacity = useSpring(1, config);
  const scale = useSpring(1, config);
  const blurPx = useSpring(0, config);
  const filter = useTransform(blurPx, (v) => `blur(${v}px)`);

  useLayoutEffect(() => {
    if (!isAnimatable) return;
    const prev = prevChar.current;
    const prevAnimKey = prevKey.current;
    prevChar.current = char;
    prevKey.current = animationKey;

    const settle = () => {
      y.set(0);
      opacity.set(1);
      scale.set(1);
      blurPx.set(0);
    };
    const run = () =>
      animationDelay <= 0
        ? settle()
        : (timer.current = setTimeout(settle, animationDelay * 1000));

    const enter = () => {
      y.jump(enterDirection === "up" ? enterY : -enterY);
      opacity.jump(0);
      scale.jump(enterScale);
      blurPx.jump(enterBlur);
      run();
    };

    if (isFirst.current) {
      isFirst.current = false;
      if (animateOnMount) enter();
      return;
    }
    if (char !== prev || (animationKey !== prevAnimKey && animationKey)) {
      if (timer.current) clearTimeout(timer.current);
      enter();
    }
  }, [
    char,
    animationKey,
    isAnimatable,
    animationDelay,
    enterY,
    enterBlur,
    enterScale,
    enterDirection,
    animateOnMount,
    y,
    opacity,
    scale,
    blurPx,
  ]);

  useEffect(() => () => clearTimeout(timer.current), []);

  const spring = { type: "spring" as const, stiffness: 320, damping: 28 };
  if (!isAnimatable) {
    return (
      <motion.span layout={layoutAnimation} className={className} transition={spring}>
        {char}
      </motion.span>
    );
  }
  return (
    <motion.div
      layout={layoutAnimation}
      className={cn(
        "relative grid place-items-center [&>*]:col-start-1 [&>*]:row-start-1",
        className,
      )}
      transition={spring}
    >
      <motion.span style={{ opacity, scale, filter, y }}>{char}</motion.span>
    </motion.div>
  );
}

interface CharSpringMorphProps {
  value: string;
  gap?: number;
  className?: string;
  staggerDelay?: number;
  direction?: "up" | "down";
  animateOnMount?: boolean;
}

/**
 * Text/number whose changed characters animate in place: on every value change
 * only the glyphs that actually differ (kept stable by place-value keys) roll
 * in with a staggered spring — blur, scale, and a directional slide inferred
 * from whether the number grew or shrank. Unchanged characters hold.
 * @param {string} value - Current value to display [Required]
 * @param {number} staggerDelay - Per-character stagger in seconds [Optional, default: 0.04]
 */
export function CharSpringMorph({
  value,
  gap = 2,
  className,
  staggerDelay = 0.04,
  direction,
  animateOnMount = false,
}: CharSpringMorphProps) {
  const hasMounted = useRef(false);
  const prevValue = useRef(value);
  const mountDelays = useRef<Map<string, number> | null>(null);
  const tokens = useMemo(() => tokenize(value), [value]);
  const changed = prevValue.current !== value;

  const prevTokens = new Map(tokenize(prevValue.current).map((t) => [t.key, t]));
  const delays = new Map<string, number>();
  let order = 0;
  for (const token of tokens) {
    const prev = prevTokens.get(token.key);
    const onMount = animateOnMount && !hasMounted.current;
    const isFreshChange =
      hasMounted.current &&
      (prev === undefined || prev.char !== token.char || changed);
    if (token.isAnimatable && (onMount || isFreshChange)) {
      delays.set(token.key, order);
      order += 1;
    }
  }
  if (mountDelays.current === null && animateOnMount && !hasMounted.current) {
    mountDelays.current = new Map(
      Array.from(delays, ([k, n]) => [k, n * staggerDelay]),
    );
  }

  const nextNum = numericValue(value);
  const prevNum = numericValue(prevValue.current);
  const enterDirection: "up" | "down" =
    direction === "up" || direction === "down"
      ? direction
      : nextNum !== undefined && prevNum !== undefined && nextNum < prevNum
        ? "down"
        : "up";

  useEffect(() => {
    hasMounted.current = true;
    prevValue.current = value;
  }, [value]);

  return (
    <motion.div
      layout
      className={cn("flex items-center tabular-nums", className)}
      style={{ gap }}
      transition={{ type: "spring", stiffness: 320, damping: 28 }}
    >
      {tokens.map((token) => (
        <Char
          key={token.key}
          char={token.char}
          isAnimatable={token.isAnimatable}
          animateOnMount={animateOnMount || hasMounted.current}
          animationKey={delays.has(token.key) ? value : ""}
          enterDirection={enterDirection}
          animationDelay={
            delays.has(token.key)
              ? (delays.get(token.key) as number) * staggerDelay
              : (mountDelays.current?.get(token.key) ?? 0)
          }
        />
      ))}
    </motion.div>
  );
}

Update the import paths to match your project setup.

Similar components

Spotlight Quotes

Prism Reveal Text

Snap Scroll Headlines

Cipher Text Reveal

Install via CLI

Resource details

PublishedJuly 17, 2026
CategoryText
ReactMotionTailwind CSS