Text Scramble
motion-primitives/text-scrambleFreeComponent
A component that creates a scrambling text effect during transitions.
Install it
npx shadcn@latest add https://raw.githubusercontent.com/ibelick/motion-primitives/HEAD/public/c/text-scramble.jsonSource
1'use client';2import { type JSX, useEffect, useState } from 'react';3import { motion, MotionProps } from 'motion/react';45export type TextScrambleProps = {6 children: string;7 duration?: number;8 speed?: number;9 characterSet?: string;10 as?: React.ElementType;11 className?: string;12 trigger?: boolean;13 onScrambleComplete?: () => void;14} & MotionProps;1516const defaultChars =17 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';1819export function TextScramble({20 children,21 duration = 0.8,22 speed = 0.04,23 characterSet = defaultChars,24 className,25 as: Component = 'p',26 trigger = true,27 onScrambleComplete,28 ...props29}: TextScrambleProps) {30 const MotionComponent = motion.create(31 Component as keyof JSX.IntrinsicElements32 );33 const [displayText, setDisplayText] = useState(children);34 const [isAnimating, setIsAnimating] = useState(false);35 const text = children;3637 const scramble = async () => {38 if (isAnimating) return;39 setIsAnimating(true);4041 const steps = duration / speed;42 let step = 0;4344 const interval = setInterval(() => {45 let scrambled = '';46 const progress = step / steps;4748 for (let i = 0; i < text.length; i++) {49 if (text[i] === ' ') {50 scrambled += ' ';51 continue;52 }5354 if (progress * text.length > i) {55 scrambled += text[i];56 } else {57 scrambled +=58 characterSet[Math.floor(Math.random() * characterSet.length)];59 }60 }6162 setDisplayText(scrambled);63 step++;6465 if (step > steps) {66 clearInterval(interval);67 setDisplayText(text);68 setIsAnimating(false);69 onScrambleComplete?.();70 }71 }, speed * 1000);72 };7374 useEffect(() => {75 if (!trigger) return;7677 scramble();78 }, [trigger]);7980 return (81 <MotionComponent className={className} {...props}>82 {displayText}83 </MotionComponent>84 );85}
What it pulls in
npm packages
Files it writes
More from motion-primitives
All 33 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| Accordionaccordion | motion-primitives | Components | Free | 1 dep | |
| Animated Backgroundanimated-background | motion-primitives | Components | Free | 1 dep | |
| Animated Groupanimated-group | motion-primitives | Components | Free | 1 dep | |
| Animated Numberanimated-number | motion-primitives | Components | Free | 1 dep | |
| Border Trailborder-trail | motion-primitives | Components | Free | 1 dep | |
| Carouselcarousel | motion-primitives | Components | Free | 1 dep | |
| Cursorcursor | motion-primitives | Components | Free | 1 dep | |
| Dialogdialog | motion-primitives | Components | Free | 1 dep · 2 files |
