Framer Motion animation example in react
Framer Motion is a popular and powerful library for React that makes creating animations easy and intuitive. Here's a basic example to get you started with Framer Motion, showcasing how to animate a simple box component when it mounts.
First, ensure you have Framer Motion installed in your project. If you haven't installed it yet, you can do so by running:
npm install framer-motion
Next, let's create a simple component that uses Framer Motion to animate. We'll make a Box component that fades and scales up when it first appears.
Box Component with Framer Motion
Create a new file named Box.js (or any name you prefer) and add the following code:
import React from 'react';
import { motion } from 'framer-motion';
const Box = () => {
return (
<motion.div
initial={{ opacity: 0, scale: 0.5 }} // Initial state of the component
animate={{ opacity: 1, scale: 1 }} // Final state of the component (visible and scaled up)
transition={{ duration: 0.5 }} // Animation duration
style={{
width: 100,
height: 100,
backgroundColor: 'salmon',
margin: '0 auto',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 20,
}}
>
Animate Me
</motion.div>
);
};
export default Box;
In this example, the motion.div component is used in place of the standard div. It accepts initial, animate, and transition props that define the animation's starting state, ending state, and how it transitions between the two, respectively.
initial: The initial appearance of the component before the animation starts. In this case, it's semi-transparent (opacity: 0) and scaled down to half its size (scale: 0.5).animate: The state the component animates to. Here, it transitions to full opacity and its original size.transition: Defines the timing and type of the transition. We're using a simple duration of 0.5 seconds.
Using the Box Component
To see the animation in action, import and use the Box component in your application's component, like so:
import React from 'react';
import Box from './Box'; // Adjust the import path according to your file structure
const App = () => {
return (
<div>
<h1>Framer Motion Example</h1>
<Box />
</div>
);
};
export default App;
Now, when you run your React application, you should see the Box component fade in and scale up when it first mounts, showcasing a simple but effective animation using Framer Motion. This example barely scratches the surface of what's possible with Framer Motion, which supports a wide range of animations, gestures, and more advanced effects for creating dynamic and interactive user experiences.