React animations / Framer Motion — Part II
Making a laser sight button — mouse move/enter/exit
The end result:
So how did I animate the laser dot movement?
Framer Motion’s motion component accepts two props we can use for this initial and animate.
Move Animation
This is actually very easy. Simply pass your mouse coordinates mx and my to their corresponding coordinates in Framer Motion’s animate property.
<motion.div
animate={{
x: mx,
y: my,
}}
/>It’s important to note the x and y in animate are shortcuts for the corresponding values intranslate3(x, y, z).
By default, Framer Motion uses a spring animation, which although maybe unrealistic, suits the movement of a laser sight quite nicely. It kind of gives the impression of trailing light.
Enter/Exit
Let’s say we want our cursor to fade in when our cursor enters our button and fades out when our cursor leaves it.
Get codebro.io’s stories in your inbox
Join Medium for free to get updates from this writer.
There are two ways we can achieve this.
- The easy way — toggle in
animate
That is, simply toggle opacity inside our animate property.
Our component then becomes
<motion.div
animate={{
x: mx,
y: my,
opacity: isActive ? 1 : 0
}}
/>For our example this is totally sufficient, because we have a variable isActive available. If, however, you wish to learn how to animate by keys or “mount”/”unmount”, keep reading.
2. The React 😎 way — initial and <AnimatePresence/>
The initial property is very useful and makes “mount” animations trivial.
<motion.div
initial={{opacity: 0}}
animate={{
x: mx,
y: my,
opacity: 1
}}
/>NB: If you want to cancel the initial “mount” animation you can set
initial={false}.
This, however, only takes care of “mount”.
For “unmount” animations we need an additional component namely <AnimatePresence/>. This is because React doesn’t have lifecycles that sufficiently handle unmounted components.
To animate both “mount” and “unmount” our component becomes
<AnimatePresence>
{isActive && (
<motion.div
key="laser-dot"
initial={{opacity: 0}}
animate={{
x: mx,
y: my,
opacity: 1
}}
exit={{opacity: 0}}
/>
)}
</AnimatePresence>NB: Our component now requires a
key!
This animation depends on the components presence and because a component’s presence will change when you change its key, we can use this to animate components by changing keys. There are some nice examples in the Framer Motion docs for this.








