How to Use Framer Motion to Create Simple Animations in React
Coding·Tue, May 6, 2025·3 min read
Installation
First, install Framer Motion using npm:
npm i framer-motion
Basic Setup
To use Framer Motion, import the necessary components and types. Here's a basic setup:
import { FC } from 'react';
import { motion } from 'framer-motion';
interface Props {
title: string;
}
const App: FC<Props> = ({ title }) => {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 1 }}
>
<h1>{title}</h1>
</motion.div>
);
};
export default App;
Example 1: Fade-In Animation
Create a simple fade-in animation using the initial
, animate
, and transition
props.
import { FC } from 'react';
import { motion } from 'framer-motion';
const FadeIn: FC = () => {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 2 }}
>
<h1>Fade-In Animation</h1>
</motion.div>
);
};
export default FadeIn;
Example 2: Slide-In Animation
Create a slide-in animation using the initial
, animate
, and transition
props.
import { FC } from 'react';
import { motion } from 'framer-motion';
const SlideIn: FC = () => {
return (
<motion.div
initial={{ x: -1000 }}
animate={{ x: 0 }}
transition={{ duration: 1 }}
>
<h1>Slide-In Animation</h1>
</motion.div>
);
};
export default SlideIn;
Example 3: Scale Animation
Create a scale animation using the whileHover
prop.
import { FC } from 'react';
import { motion } from 'framer-motion';
const Scale: FC = () => {
return (
<motion.div
whileHover={{ scale: 1.2 }}
transition={{ duration: 0.5 }}
>
<h1>Hover to Scale</h1>
</motion.div>
);
};
export default Scale;
Example 4: Rotate Animation
Create a rotate animation using the whileTap
prop.
import { FC } from 'react';
import { motion } from 'framer-motion';
const Rotate: FC = () => {
return (
<motion.div
whileTap={{ rotate: 360 }}
transition={{ duration: 0.5 }}
>
<h1>Tap to Rotate</h1>
</motion.div>
);
};
export default Rotate;
Error Handling
Always handle potential errors gracefully. For example, ensure that the component receives the correct props:
import { FC } from 'react';
import { motion } from 'framer-motion';
interface Props {
title: string;
}
const App: FC<Props> = ({ title }) => {
if (!title) {
throw new Error('Title is required');
}
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 1 }}
>
<h1>{title}</h1>
</motion.div>
);
};
export default App;
Conclusion
Framer Motion is a powerful library for creating animations in React. By following this tutorial, you've learned how to set up Framer Motion and create four different types of animations. Experiment with these examples to enhance your React applications with smooth and engaging animations.
For more advanced usage, refer to the Framer Motion documentation.