Adding interactive animations: Day 1
Let's see how to add an interactive drag animation using tailwind and framer-motion in NextJS
Welcome to Day 1 of learning how to make our websites look cool!
It's always the little things that can spark up things, and so is true for websites. So I decided to make a short blog series just for that :)
What exactly are we building today?
Simple. A draggable (& throwable) image component for our NextJS website👇
Why are we building it?
Because why not? it's easy, cool and perfect to add interactivity xD
You Ready?
Let's break down the whole thing in 3 small steps👇
Step: 0 -> Installing dependencies
Step: 1 ->Setting Up Your Component
Step: 2 ->Adding Image
Step: 3 ->Adding the magic code
So, without further ado, let's get coding🚀
1. Installing dependencies
We need two things:
- TailwindCSS (lifesaver, honestly) and
- framer-motion (one of the coolest animation library out there)
To get Framer Motion onboard, simply run:
npm i framer-motion
TailwindCSS setup comes out of the box for us NextJS users, so we're ready to roll!
But if you're using React or something, refer docs for installing tailwind🤓
2. Setting Up Your Component
Let's init our component.
Don't forget to enable client-side rendering with "use client";
"use client";
import { useRef } from 'react';
import { motion } from 'framer-motion';
export default function Cool() {
return (
<div>Cool</div>
)
}
WhyuseRef
?
useRef
is crucial for our draggable feature. It allows us to reference the parent container, setting boundaries for our draggable image, ensuring it doesn't float away into the abyss.
3. Adding image
Let's add the image, make sure it's placed in your public
folder.
export default function Cool() {
const constraintsRef = useRef(null);
return (
<div className='min-h-screen w-full relative' ref={constraintsRef}>
<motion.img
src='dreg.png'
className=' absolute top-10 right-10 '
</motion.img>
By using the absolute
class and adjusting the top
/ bottom
and left
/ right
classes, we define the initial position of our image. And don't forget to add relative
to the parent div.
4. Adding the magic code
Leme spill the secret sauce & let's bring our component to life.
<motion.img
src='dreg.png'
className='absolute top-10 right-10'
drag // Enables dragging
dragConstraints={constraintsRef} // Confines the drag within the parent div
/>
And just like that, we've added interactivity to our website!
I hope you had fun and learned something new today. Don't forget to connect with me and share your thoughts.
See you on the next one!!
❤️Follow me on Twitter to know more about me!
💕 Also subscribe to my Youtube Channel!