MERRY-GO-ROUND : Carousel Component

Madhav Ganesan - Jul 3 - - Dev Community

In the rapidly changing world of social media, from Instagram to Facebook and LinkedIn, one feature stands out for its ability to capture attention and convey a wealth of information in an engaging way: "The Carousel".

Carousels provide a dynamic way to present large amounts of content in a cyclic and visually appealing format, moving beyond the monotony of traditional bullet points. This feature allows you to showcase multiple pieces of content within a single post, creating an interactive and engaging experience for your audience.

Image description

Why Carousels?

Using carousels to present your content offers several advantages:

  • Increased Engagement
  • Highly space efficiency
  • Visual Appeal
  • Organized Content

Carousel Implementation:

Pre-requisites:
In this blog, I'm going to implement using these technologies:
1) Nextjs
2) Tailwind CSS

1)Boiler code for carousel:

const Carousel = ({ slides }) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const slideRef = useRef(null);

  const goToNextSlide = () => {
    setCurrentIndex((prevIndex) => (prevIndex + 1) % slides.length);
  };

  const goToPreviousSlide = () => {
    setCurrentIndex((prevIndex) =>
      prevIndex === 0 ? slides.length - 1 : prevIndex - 1
    );
  };

  useEffect(() => {
    if (slideRef.current) {
      slideRef.current.style.transform = `translateX(-${currentIndex * 100}%)`;
    }
  }, [currentIndex]);

  return (
    <div className="relative sm:w-3/4 w-full overflow-hidden">
      <div
        ref={slideRef}
        className="flex transition-transform duration-500 ease-in-out"
      >
        {slides.map((slide, index) => (
          <div key={index} className="min-w-full bg-white flex flex-col pb-2 rounded-lg shadow-lg">
            {slide}
          </div>
        ))}

      </div>
      <button
        className="absolute top-1/2 transform -translate-y-1/2 left-4 bg-gray-800 text-white w-10 h-10 p-2 rounded-full"
        onClick={goToPreviousSlide}
      >
        Previous;
      </button>
      <button
        className="absolute top-1/2 transform -translate-y-1/2 right-4 bg-gray-800 text-white w-10 h-10 p-2 rounded-full"
        onClick={goToNextSlide}
      >
        Next;
      </button>
    </div>
  );
};

export default Carousel;

Enter fullscreen mode Exit fullscreen mode

Code Explanation:

1) Creating the Reference:

const slideRef = useRef(null);

Enter fullscreen mode Exit fullscreen mode

The 'ref' attribute in React is used to attach the reference to a specific DOM element. In this code, the reference is attached to the container

that holds the slides:
<div
  ref={slideRef}
  className="flex transition-transform duration-500 ease-in-out"
>
  {slides.map((slide, index) => (
    <div key={index} className="min-w-full bg-white flex flex-col pb-2 rounded-lg shadow-lg">
      {slide}
    </div>
  ))}
</div>

Here, 'slideRef' is assigned to the ref attribute of the div element. When this component is rendered, React sets slideRef.current to the corresponding DOM element.

2) Accessing the DOM Element:

The 'current' property of the reference object will now point to the actual DOM element. This allows you to interact directly with the DOM element in your component.

useEffect(() => {
  if (slideRef.current) {
    slideRef.current.style.transform = `translateX(-${currentIndex * 100}%)`;
  }
}, [currentIndex]);

'slideRef.current.style.transform = translateX(-${currentIndex * 100}%)' - updates the transform style property of that DOM element to move it horizontally based on the current index.

3) Previous and Next Buttons:

Button: Previous

      <button
        className="absolute top-1/2 transform -translate-y-1/2 left-4 bg-gray-800 text-white w-10 h-10 p-2 rounded-full"
        onClick={goToPreviousSlide}
      >
        &lt;
      </button>

Button: Next

      </button>
      <button
        className="absolute top-1/2 transform -translate-y-1/2 right-4 bg-gray-800 text-white w-10 h-10 p-2 rounded-full"
        onClick={goToNextSlide}
      >
        &gt;
      </button>

Feel free to reach out if you have any questions or need further assistance. 😊📁✨

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .