Search code examples
javascripthtmlreactjstailwind-cssframer-motion

How to maintain the space between the words in a map


I am trying to animate text with Framer Motion. However, I need to animate the text letter by letter. When I split them and try to reallocate, they lose the space between the words. If I pass 'Web Developer' the result will be 'WebDeveloper'. Is there a way to maintain the space?

import { motion } from 'framer-motion'

type Props = {
    text: string
}

function AnimatedText({ text }: Props) {

    const characters = text.split('')

    return (
        <>
                <div className='flex'>
                    {characters.map((char, index) => (
                        <motion.div
                            key={index}
                            initial={{ opacity: 0, y: 15 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: 0.04 * index }}
                        >
                            {char}
                        </motion.div>
                    ))}
                </div>
        </>
    )
}

export default AnimatedText

Solution

  • You could apply white-space: pre to the motion.div element - but then you would need to eliminate the additional white-space you got before and after {char} there. Replacing the space with a non-breaking space should also work.