Pavan Jadhaw
Blog

Animate svg using framer motion

Subtle animations are great way to add spark in your web projects and framer motion will allow us to do just that. Framer motion is animation library for react with simple api for animations and gestures.

If you want to animate svg path make sure that svg you are animating is stroke based.

Svg for below sun icon.

<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
width="100"
height="100"
>
<path
stroke="white"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"
/>
</svg>

Getting started with framer motion

Motion requires React 16.8 or greater.

yarn add framer-motion

Motion components are the core of the Motion API. There's a motion component for every HTML and SVG element. They work exactly the same, with additional props that allow you to declaratively add animations and gestures.

Converting svg to motion components.

import { motion } from 'framer-motion';
function SunIcon() {
return (
<motion.svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
width="100"
height="100"
>
<motion.path
stroke="white"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"
/>
</motion.svg>
);
}
export default SunIcon;

Animating opacity.

<motion.path
...
// animation start state
initial={{
opacity: 0,
}}
// animation end state
animate={{
opacity: 1,
}}
...
/>

Animating rotate.

<motion.path
...
initial={{
opacity: 0,
rotate: -45,
}}
animate={{
opacity: 1,
rotate: 0,
}}
...
/>

Animating pathlength.

motion.path components have access to three convenience SVG path properties:

These are all set as a value between 0 and 1, where 1 is the measured length of the path.

<motion.path
...
initial={{
opacity: 0,
rotate: -45,
pathLength: 0,
}}
animate={{
opacity: 1,
rotate: 0,
pathLength: 1,
}}
...
/>

Animation duration and transition effect

A Transition is an object that defines how values animate from one state to another.

This object can contain Orchestration props like delay, that schedule the animation as a whole.

<motion.path
...
transition={{
duration: 3,
ease: 'easeInOut',
}}
...
/>

Bonus: Looping animations

Setting repeat to Infinity will repeat animation perpetualy. Without setting repeatType, it will loop the animation.

repeatType: "loop" | "reverse" | "mirror"
How to repeat the animation.
This can be either:

<motion.path
...
transition={{
duration: 3,
ease: 'easeInOut',
repeat: Infinity,
repeatType: 'reverse',
}}
...
/>

Further readings.

motion api
motion components

Acknowledgements

heroicons.com - for Beautiful hand-crafted SVG icons