I’m using the framer-motion library to create a rotating text effect inside a resizable box on my website. The goal is to make the box adjust its size smoothly as the text changes. When the text gets longer, the box grows nicely, but when the text gets shorter, it suddenly jumps to the new size instead of transitioning smoothly. I need help fixing this so the box adjusts smoothly whether the text gets longer or shorter.
Current implementation
interface RotatingTextProps {
words: string[];
}
function RotatingText(props: RotatingTextProps) {
const { words } = props;
const theme = useTheme();
const [current, setCurrent] = React.useState(0);
React.useEffect(() => {
const interval = setInterval(
() => setCurrent((current) => (current + 1) % words.length),
1000 * 2
);
return () => clearInterval(interval);
}, []);
return (
<motion.div
layout
transition={{ width: 'auto', duration: 0.5 }}
style={{
backgroundColor: theme.palette.primary.main,
display: 'inline-block',
}}
>
<h1
style={{
display: 'inline-grid',
overflow: 'hidden',
}}
>
<AnimatePresence initial={false}>
<motion.span
key={current}
initial={{ transform: 'translateY(100%)', opacity: 0 }}
animate={{ transform: 'translateY(0%)', opacity: 1 }}
exit={{ transform: 'translateY(-100%)', opacity: 0 }}
transition={{ duration: 0.5, ease: 'easeInOut' }}
style={{ display: 'inline-block', gridColumn: 1, gridRow: 1 }}
>
{words[current]}
</motion.span>
</AnimatePresence>
</h1>
</motion.div>
);
}
Andrius is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.