To implement a dynamic image carousel with Framer Motion in Next.js, you can follow these steps:
Set up a Next.js project: Make sure you have a Next.js project initialized. You can create one using the following commands:
bashnpx create-next-app my-carousel-app
cd my-carousel-app
Install dependencies: Install Framer Motion and any other necessary packages:
bashnpm install framer-motion
Create a new component for the image carousel:
Inside the components
folder, create a new component for your image carousel. For example, ImageCarousel.js
.
jsx// components/ImageCarousel.js
import { motion } from 'framer-motion';
const ImageCarousel = ({ images }) => {
return (
<div className="carousel-container">
{images.map((image, index) => (
<motion.img
key={index}
src={image}
alt={`Image ${index + 1}`}
className="carousel-image"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
/>
))}
</div>
);
};
export default ImageCarousel;
Use the ImageCarousel component in your page:
In the pages directory (e.g., pages/index.js
), import and use the ImageCarousel
component. You can fetch dynamic images from an API or use static images.
jsx// pages/index.js
import ImageCarousel from '../components/ImageCarousel';
const images = [
'/images/image1.jpg',
'/images/image2.jpg',
'/images/image3.jpg',
];
const Home = () => {
return (
<div>
<h1>Dynamic Image Carousel</h1>
<ImageCarousel images={images} />
</div>
);
};
export default Home;
Add styling:
Style your carousel as needed. You can use CSS or a styling library like styled-components
. Here's a simple example:
css/* styles/globals.css */
.carousel-container {
display: flex;
overflow: hidden;
width: 100%;
max-width: 600px;
margin: 0 auto;
}
.carousel-image {
width: 100%;
height: auto;
}
Run your Next.js app: Start your Next.js development server:
bashnpm run dev
Visit http://localhost:3000
in your browser to see your dynamic image carousel.
Note: Make sure to replace the image paths with your actual image paths or URLs. Additionally, you can enhance the carousel with additional features like automatic sliding, navigation buttons, etc., based on your requirements.