Animated Background
motion-primitives/animated-backgroundFreeComponent
A component that provides animated background effects for UI elements.
Install it
npx shadcn@latest add https://raw.githubusercontent.com/ibelick/motion-primitives/HEAD/public/c/animated-background.jsonSource
1'use client';2import { cn } from '@/lib/utils';3import { AnimatePresence, Transition, motion } from 'motion/react';4import {5 Children,6 cloneElement,7 ReactElement,8 useEffect,9 useState,10 useId,11} from 'react';1213export type AnimatedBackgroundProps = {14 children:15 | ReactElement<{ 'data-id': string }>[]16 | ReactElement<{ 'data-id': string }>;17 defaultValue?: string;18 onValueChange?: (newActiveId: string | null) => void;19 className?: string;20 transition?: Transition;21 enableHover?: boolean;22};2324export function AnimatedBackground({25 children,26 defaultValue,27 onValueChange,28 className,29 transition,30 enableHover = false,31}: AnimatedBackgroundProps) {32 const [activeId, setActiveId] = useState<string | null>(null);33 const uniqueId = useId();3435 const handleSetActiveId = (id: string | null) => {36 setActiveId(id);3738 if (onValueChange) {39 onValueChange(id);40 }41 };4243 useEffect(() => {44 if (defaultValue !== undefined) {45 setActiveId(defaultValue);46 }47 }, [defaultValue]);4849 return Children.map(children, (child: any, index) => {50 const id = child.props['data-id'];5152 const interactionProps = enableHover53 ? {54 onMouseEnter: () => handleSetActiveId(id),55 onMouseLeave: () => handleSetActiveId(null),56 }57 : {58 onClick: () => handleSetActiveId(id),59 };6061 return cloneElement(62 child,63 {64 key: index,65 className: cn('relative inline-flex', child.props.className),66 'data-checked': activeId === id ? 'true' : 'false',67 ...interactionProps,68 },69 <>70 <AnimatePresence initial={false}>71 {activeId === id && (72 <motion.div73 layoutId={`background-${uniqueId}`}74 className={cn('absolute inset-0', className)}75 transition={transition}76 initial={{ opacity: defaultValue ? 1 : 0 }}77 animate={{78 opacity: 1,79 }}80 exit={{81 opacity: 0,82 }}83 />84 )}85 </AnimatePresence>86 <div className='z-10'>{child.props.children}</div>87 </>88 );89 });90}
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 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 | |
| Disclosuredisclosure | motion-primitives | Components | Free | 1 dep |
