Up
Down
Left
Right
Usage
Install the framer-motion library.
npm install framer-motion
Copy the code above and paste it into your project.
'use client'
import { useMemo } from 'react'
import { motion, Variants } from 'framer-motion'
type FadeTextProps = {
className?: string
direction?: 'up' | 'down' | 'left' | 'right'
duration?: number
delay?: number
framerProps?: Variants
children: React.ReactNode
}
export function FadeText({
direction = 'up',
className,
duration = 0.8,
delay = 0,
framerProps = {
hidden: { opacity: 0 },
show: { opacity: 1, transition: { type: 'spring', duration, delay } },
},
children,
}: FadeTextProps) {
const directionOffset = useMemo(() => {
const map = { up: 10, down: -10, left: -10, right: 10 }
return map[direction]
}, [direction])
const axis = direction === 'up' || direction === 'down' ? 'y' : 'x'
const FADE_ANIMATION_VARIANTS = useMemo(() => {
const { hidden, show, ...rest } = framerProps as {
[name: string]: { [name: string]: number; opacity: number }
}
return {
...rest,
hidden: {
...(hidden ?? {}),
opacity: hidden?.opacity ?? 0,
[axis]: hidden?.[axis] ?? directionOffset,
},
show: {
...(show ?? {}),
opacity: show?.opacity ?? 1,
[axis]: show?.[axis] ?? 0,
},
}
}, [directionOffset, axis, framerProps])
return (
<motion.div
initial="hidden"
animate="show"
viewport={{ once: true }}
variants={FADE_ANIMATION_VARIANTS}
>
<motion.div className={className}>{children}</motion.div>
</motion.div>
)
}