DEV Community

Cover image for Creating Smooth Animations in React with Framer-Motion
ayka.code
ayka.code

Posted on • Updated on

Creating Smooth Animations in React with Framer-Motion

React.js is a popular JavaScript library for building user interfaces. It allows you to create reusable components that can be shared among different parts of your application. Framer-motion is a popular animation library for React that makes it easy to create smooth, gesture-based animations.

Here is a simple tutorial on how to use React.js and Framer-motion together to create an animated button:

First, you will need to make sure that you have React.js and Framer-motion installed in your project. You can do this by running the following command:

npm install react react-dom framer-motion
Enter fullscreen mode Exit fullscreen mode

Next, create a new file called "Button.js" and add the following code:

import React from 'react';
import { motion } from 'framer-motion';

const Button = ({ onClick }) => {
  return (
    <motion.button
      onClick={onClick}
      whileHover={{ scale: 1.1 }}
      whileTap={{ scale: 0.95 }}
    >
      Click me!
    </motion.button>
  );
};

export default Button;
Enter fullscreen mode Exit fullscreen mode

This code creates a new Button component that uses the motion.button component provided by Framer-motion. When the button is hovered over, it will animate to a scale of 1.1. When the button is tapped, it will animate to a scale of 0.95.

To use this Button component in your application, you can import it and add it to your JSX like this:

import Button from './Button';

const App = () => {
  return (
    <div>
      <Button onClick={() => console.log('Button was clicked!')} />
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode

This code creates a new App component that uses the Button component. When the button is clicked, it will log a message to the console.

You can learn more about React.js and Framer-motion by reading the documentation and exploring the examples on their respective websites.

Top comments (0)