Created
April 24, 2023 07:47
-
-
Save phillippbertram/1064c18a5beb05052ee4f23df6b198af to your computer and use it in GitHub Desktop.
Simple React Tex Loop Component using Framer Motion and tailwind.css
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from "react"; | |
import { AnimatePresence, motion } from "framer-motion"; | |
export type TextLoopProps = React.PropsWithChildren & { | |
interval?: number; | |
delay?: number; | |
}; | |
export const TextLoop: React.FC<TextLoopProps> = ({ | |
interval = 3000, | |
delay = 0, | |
children, | |
}) => { | |
const [index, setIndex] = useState(0); | |
useEffect(() => { | |
setTimeout(() => { | |
let next = index + 1; | |
if (next === React.Children.count(children)) { | |
next = 0; | |
} | |
setIndex(next); | |
}, interval); | |
}, [index, setIndex]); | |
return ( | |
<div className="inline-block relative w-full align-top"> | |
<AnimatePresence> | |
<motion.span | |
className="absolute" | |
variants={{ | |
enter: () => { | |
return { | |
y: "90%", | |
opacity: 0, | |
}; | |
}, | |
center: { | |
zIndex: 1, | |
y: 0, | |
opacity: 1, | |
}, | |
exit: () => { | |
return { | |
y: "-90%", | |
zIndex: 1, | |
opacity: 0, | |
}; | |
}, | |
}} | |
key={index} | |
initial="enter" | |
animate="center" | |
exit="exit" | |
transition={{ | |
ease: "easeInOut", | |
delay: delay, | |
duration: 0.3, | |
}} | |
> | |
{React.Children.toArray(children)[index]} | |
</motion.span> | |
</AnimatePresence> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment