So, I’ve been diving into Framer Motion lately and decided to create the classic: Typewriter effect. It looks super professional, but once you break it down, the logic is actually really elegant. Here’s how I built it and what I learned along the way.
1. The Strategy: Break It Down
const characters = Array.from(text);
The first thing the code does is split the text. We use Array.from(text) to turn a string into an array of individual characters.
The reason for this is simple: to animate each character individually, they each need their own "seat" (an HTML element) in the DOM. If the text stayed as one long string, Framer Motion would just animate the whole block at once.
2. The Power of Variants
This is where it gets cool. I learned and used a concept called Variants in Framer Motion. Think of variants as "labels" for your animation states. Instead of writing messy inline styles, you define a hidden state and a visible state.
const containerVariants = {
hidden: { opacity: 1 },
visible: {
opacity: 1,
transition: {
delayChildren: delay,
staggerChildren: duration,
},
},
};
const characterVariants = {
hidden: { opacity: 0, y: 5 },
visible: {
opacity: 1,
y: 0,
transition: {
type: "spring" as AnimationGeneratorType,
damping: 12,
stiffness: 200,
},
},
};
What’s powerful here is the Parent-Child control. By giving the container a variant label like "visible," it automatically tells all the children (the letters) to switch to their "visible" state too. It’s like a conductor leading an orchestra.
3. The "Double Hiding" Gotcha
One thing that tripped me up was setting the container's opacity. You’ll notice in the hidden variant, the container is actually set to opacity: 1.
Wait, why? Well, if the container is hidden and the letters are hidden, you get "double hiding." When the animation starts, the whole box would fade in while the letters are also fading in—it looks messy. By keeping the container at opacity: 1, the "box" is always there, and we only see the magic of the letters appearing one by one.
4. Orchestration: Staggering
The "typewriter" feel comes from two specific transition properties:
- delayChildren: This sets a countdown before the first letter even thinks about moving.
- staggerChildren: This is the secret sauce. It sets a tiny time gap (like 0.05s) between each subsequent character. Instead of a "pop," you get that rhythmic, rolling reveal.
5. Adding Some "Spring"
Instead of a boring, flat animation, I used a spring transition for the characters. By playing with stiffness and damping, the letters don't just appear—they kind of snap into place with a bit of life. It makes the digital text feel a bit more tactile and physical.
What's next?
Now that We've got the basics down, we can try thinking about how to speed it up. If we wanted to write "two words at a time" for a faster read, how can we achieve that?
Top comments (0)