I have decided to create my own carasoual instead of using react-slick for less space. I…
- User
I have decided to create my own carasoual instead of using react-slick for less space. I want to make the SwipeCarousel styling and the look exactly like the previous carousel (react-slick) for example the content on the carousel, the black gradient on the top, the dots... everything exactly like the previous one on the styling... keep the functionality of the current swipecarousel as it is... new SwipeCarousel.jsx: 'use client' import React, { useEffect, useState } from "react"; import { motion, useMotionValue } from "framer-motion";
const imgs = [ "/hero.png", "/woman.png", "/shoes.png", ];
const ONE_SECOND = 1000; const AUTO_DELAY = ONE_SECOND * 10; const DRAG_BUFFER = 50;
const SPRING_OPTIONS = { type: "spring", mass: 3, stiffness: 400, damping: 50, };
export const SwipeCarousel = () => { const [imgIndex, setImgIndex] = useState(0);
const dragX = useMotionValue(0);
useEffect(() => { const intervalRef = setInterval(() => { const x = dragX.get();
if (x === 0) { setImgIndex((pv) => { if (pv === imgs.length - 1) { return 0; } return pv + 1; }); } }, AUTO_DELAY); return () => clearInterval(intervalRef);}, []);
const onDragEnd = () => { const x = dragX.get();
if (x <= -DRAG_BUFFER && imgIndex < imgs.length - 1) { setImgIndex((pv) => pv + 1); } else if (x >= DRAG_BUFFER && imgIndex > 0) { setImgIndex((pv) => pv - 1); }};
return ( <motion.div drag="x" dragConstraints={{ left: 0, right: 0, }} style={{ x: dragX, }} animate={{ translateX:
-${imgIndex * 100}%, }} transition={SPRING_OPTIONS} onDragEnd={onDragEnd} className="flex cursor-grab items-center active:cursor-grabbing" > </motion.div><Dots imgIndex={imgIndex} setImgIndex={setImgIndex} /> <GradientEdges /> </div>);
};
const Images = ({ imgIndex }) => { return ( <> {imgs.map((imgSrc, idx) => { return ( <motion.div key={idx} style={{ backgroundImage: url(${imgSrc}), backgroundSize: "cover", backgroundPosition: "center", }} animate={{ scale: imgIndex === idx ? 0.95 : 0.85, }} transition={SPRING_OPTIONS} className="aspect-video w-screen shrink-0 rounded-xl bg-neutral-800 object-cover" /> ); })} </> ); };
const Dots = ({ imgIndex, setImgIndex }) => { return (
{imgs.map((_, idx) => { return ( <button key={idx} onClick={() => setImgIndex(idx)} className={h-3 w-3 rounded-full transition-colors ${ idx === imgIndex ? "bg-neutral-50" : "bg-neutral-500" }} /> ); })}
); };
const GradientEdges = () => { return ( <>
</> ); }; Old one: 'use client';
import React, { useState, useRef } from 'react'; import dynamic from 'next/dynamic'; const CarouselSlide = dynamic(() => import('@/components/carousel/CarouselSlide').then(mod => mod.CarouselSlide), { ssr: true }); const CustomDots = dynamic(() => import('@/components/carousel/CustomDots').then(mod => mod.CustomDots), { ssr: true }); const Slider = dynamic(() => import("react-slick"), { loading: () => , });
const Carousel = () => { const [activeSlide, setActiveSlide] = useState(0); const sliderRef = useRef(null);
const slides = [ { image: '/hero.png', title: 'Find Our Women Jacket', buttonText: 'Discover more', }, { image: '/shoes.png', title: 'Explore New Arrivals', buttonText: 'Shop Now', }, { image: '/bags.png', title: 'Summer Collection', buttonText: 'Browse Collection', }, { image: '/woman.png', title: 'Exclusive Offers', buttonText: 'Learn More', }, // Add more slides as needed ];
const settings = { dots: false, infinite: true, speed: 500, slidesToShow: 1, slidesToScroll: 1, autoplay: true, autoplaySpeed: 5000, pauseOnHover: false, arrows: false, beforeChange: (current, next) => setActiveSlide(next), accessibility: true, adaptiveHeight: true, swipeToSlide: true, touchThreshold: 10, useCSS: true, useTransform: true, };
const handleDotClick = (index) => { if (sliderRef.current) { sliderRef.current.slickGoTo(index); } };
return ( <Slider ref={sliderRef} {...settings}> {slides.map((slide, index) => ( <CarouselSlide key={index} {...slide} /> ))} );
}; const SliderSkeleton = () => { return
}; export default Carousel; CustomDots.jsx: import React from "react";
export const CustomDots = ({ onDotClick, activeIndex, slidesLength }) => (
{[...Array(slidesLength)].map((_, i) => ( <button key={i} onClick={() => onDotClick(i)} className={size-1 relative rounded-full transition-all duration-300 ease-in-out {i === activeIndex ? 'bg-black after:size-2.5 after:block after:rounded-full after:absolute after:bg-transparent after:border-black after:border after:bottom-0 after:top-1/2 after:left-1/2 after:-translate-x-1/2 after:-translate-y-1/2 after:right-0 ' : 'bg-black'}} aria-label={Go to slide {i + 1}} /> ))}
); import Image from "next/image"; import React from "react";
export const CarouselSlide = ({ image, title, buttonText }) => ( <Image src={image} alt={title} fill style={{ objectFit: 'cover' }} priority /> {title} {buttonText} );
- Assistant
Creating a custom
SwipeCarouselthat matches the look and functionality of your existingreact-slickcarousel involves several steps. You need to ensure that all visual elements (images, gradients, titles, buttons, dots) and functionalities (swiping, autoplay, dot navigation) are replicated accurately. Below is a comprehensive guide to help you achieve this.1. Structure Your Slides Data
First, update your slides data to include not just image paths but also titles and button texts, similar to your old carousel.
const slides = [ { image: '/hero.png', title: 'Find Our Women Jacket', buttonText: 'Discover more', }, { image: '/shoes.png', title: 'Explore New Arrivals', buttonText: 'Shop Now', }, { image: '/bags.png', title: 'Summer Collection', buttonText: 'Browse Collection', }, { image: '/woman.png', title: 'Exclusive Offers', buttonText: 'Learn More', }, // Add more slides as needed ];2. Update the SwipeCarousel Component
Modify your
SwipeCarousel.jsxto incorporate titles, buttons, and gradient overlays similar to your old carousel. Here's the updated version:'use client'; import React, { useEffect, useState } from "react"; import { motion, useMotionValue } from "framer-motion"; import Image from "next/image"; // Import Next.js Image for optimization import classNames from "classnames"; // Optional: For conditional class names const slides = [ { image: '/hero.png', title: 'Find Our Women Jacket', buttonText: 'Discover more', }, { image: '/shoes.png', title: 'Explore New Arrivals', buttonText: 'Shop Now', }, { image: '/bags.png', title: 'Summer Collection', buttonText: 'Browse Collection', }, { image: '/woman.png', title: 'Exclusive Offers', buttonText: 'Learn More', }, // Add more slides as needed ]; const ONE_SECOND = 1000; const AUTO_DELAY = ONE_SECOND * 10; const DRAG_BUFFER = 50; const SPRING_OPTIONS = { type: "spring", mass: 3, stiffness: 400, damping: 50, }; export const SwipeCarousel = () => { const [imgIndex, setImgIndex] = useState(0); const dragX = useMotionValue(0); useEffect(() => { const intervalRef = setInterval(() => { const x = dragX.get(); if (x === 0) { setImgIndex((prev) => (prev === slides.length - 1 ? 0 : prev + 1)); } }, AUTO_DELAY); return () => clearInterval(intervalRef); }, [dragX]); const onDragEnd = (event, info) => { const offset = info.offset.x; const velocity = info.velocity.x; if (offset < -DRAG_BUFFER || velocity < -500) { // Swipe left setImgIndex((prev) => (prev < slides.length - 1 ? prev + 1 : prev)); } else if (offset > DRAG_BUFFER || velocity > 500) { // Swipe right setImgIndex((prev) => (prev > 0 ? prev - 1 : prev)); } }; return ( <div className="relative overflow-hidden bg-neutral-950 py-8"> <motion.div drag="x" dragConstraints={{ left: 0, right: 0 }} style={{ x: dragX }} animate={{ x: `-${imgIndex * 100}%` }} transition={SPRING_OPTIONS} onDragEnd={onDragEnd} className="flex cursor-grab items-center active:cursor-grabbing" > {slides.map((slide, idx) => ( <Slide key={idx} slide={slide} active={idx === imgIndex} /> ))} </motion.div> <Dots imgIndex={imgIndex} setImgIndex={setImgIndex} /> <GradientOverlay /> </div> ); }; const Slide = ({ slide, active }) => { return ( <div className="relative flex-shrink-0 w-full h-96"> <Image src={slide.image} alt={slide.title} layout="fill" objectFit="cover" className="rounded-xl" priority={active} // Optimize loading for active slide /> <div className="absolute top-0 left-0 right-0 h-44 bg-gradient-to-b from-black via-transparent to-transparent rounded-xl"></div> <div className="absolute bottom-24 left-8 text-white font-chivo"> <h2 className="text-2xl font-medium mb-4 max-w-[204px] leading-tight"> {slide.title} </h2> <button className="border border-white px-4 py-2 text-xs rounded hover:bg-white hover:text-black transition-colors duration-300 ease-in-out"> {slide.buttonText} </button> </div> </div> ); }; const Dots = ({ imgIndex, setImgIndex }) => { return ( <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 flex space-x-2"> {slides.map((_, idx) => ( <button key={idx} onClick={() => setImgIndex(idx)} className={classNames( "h-3 w-3 rounded-full transition-colors", idx === imgIndex ? "bg-neutral-50" : "bg-neutral-500" )} aria-label={`Go to slide ${idx + 1}`} /> ))} </div> ); }; const GradientOverlay = () => { return ( <div className="absolute top-0 left-0 right-0 h-44 bg-gradient-to-b from-black via-transparent to-transparent"></div> ); };3. Explanation of Changes
-
Slides Data Structure:
- The
slidesarray now contains objects withimage,title, andbuttonTextto mirror the structure of your old carousel.
- The
-
Slide Component:
- Created a
Slidecomponent that replicates the structure of yourCarouselSlidecomponent. - Utilizes Next.js's
Imagecomponent for optimized image loading. - Includes a gradient overlay and absolute positioning for titles and buttons to match the old design.
- Created a
-
Dots Component:
- Modified the
Dotscomponent to position the dots at the bottom center with spacing. - Uses conditional styling to highlight the active dot.
- Added
aria-labelfor accessibility, mirroring yourCustomDotscomponent.
- Modified the
-
Gradient Overlay:
- The
GradientOverlaycomponent adds a consistent gradient at the top of the carousel, similar to the old implementation.
- The
-
Swiping and Autoplay Logic:
- Enhanced
onDragEndto consider velocity for better swipe detection. - Ensured the autoplay interval advances the slide only when the carousel is not being interacted with.
- Enhanced
-
Styling Adjustments:
- Ensured that the carousel maintains similar padding, background color, and overall layout as the old version.
- Used Tailwind CSS classes to match the styling. Adjust these classes as needed to fit your exact design specifications.
4. Additional Recommendations
-
Responsive Design:
- Ensure that your carousel is responsive across different device sizes. You might need to adjust heights, font sizes, and padding based on screen sizes using Tailwind’s responsive utilities.
-
Accessibility:
- Adding
arialabels to buttons improves accessibility. - Consider keyboard navigation for better user experience.
- Adding
-
Performance Optimization:
- Utilize the
priorityprop in theImagecomponent for the active slide to ensure it loads quickly. - Lazy load other images if necessary.
- Utilize the
-
Styling Enhancements:
- You can adjust the gradient colors, overlay heights, and other styles to better match your desired look.
- For smoother transitions, experiment with different
SPRING_OPTIONSsettings.
-
Handling Edge Cases:
- Ensure that rapid swiping or clicking on dots doesn't break the carousel’s state.
- Test the carousel thoroughly on different browsers and devices to ensure consistent behavior.
5. Final Integration
Replace your existing
SwipeCarousel.jsxwith the updated code above. Ensure that all related styles and dependencies (likeclassNamesif used) are properly installed and configured in your project.# If you choose to use classNames for conditional classes npm install classnames6. Sample Tailwind CSS Classes Explanation
-
Container Div (
relative overflow-hidden bg-neutral-950 py-8):relativesets the positioning context for absolutely positioned children.overflow-hiddenhides overflowing content, essential for carousel sliding.bg-neutral-950sets a dark background.py-8adds vertical padding.
-
Dots Container (
absolute bottom-4 left-1/2 transform -translate-x-1/2 flex space-x-2):- Positions the dots absolutely at the bottom center.
flexandspace-x-2add spacing between dots.
-
Dots (
h-3 w-3 rounded-fulletc.):- Defines the size and shape of the navigation dots.
- Conditional classes change the color based on the active slide.
-
Gradient Overlay (
absolute top-0 left-0 right-0 h-44 bg-gradient-to-b ...):- Adds a gradient that fades from black to transparent.
- Helps in making the text readable against varying image backgrounds.
Feel free to tweak the Tailwind classes to better match your exact design requirements.
7. Conclusion
By following the steps above, you can create a custom
SwipeCarouselthat closely mimics the appearance and functionality of your previousreact-slickcarousel. Ensure to test the carousel thoroughly to match all interactive behaviors and visual styles. Adjust the styling and logic as needed to fit your specific use case and design preferences.If you encounter any issues or need further customization, feel free to ask!
-