37 - Image Carousel with Autoplay

Description

Develop a React component showcasing images in a rotating carousel with automatic slideshow and manual navigation.

  • Displays multiple images within a rotating carousel.

  • Automatically transitions between images at a specified interval (autoplay).

  • Provides controls for manual navigation (previous/next buttons).

  • Optionally displays image captions or other information.

Algorithm

  1. Component Structure:

    • Define a functional component named ImageCarousel.

    • Accept props for:

      • images: Array of image objects (URL, caption, etc.).

      • autoplaySpeed: Interval for automatic image transition (optional).

    • Maintain internal state for:

      • currentIndex: Index of the currently displayed image.

  2. Automatic Slideshow (optional):

    • Use useEffect with the autoplaySpeed prop to set a timer for automatic image transition.

    • Update the currentIndex state inside the effect handler to progress through the images.

  3. Image Display and Rendering:

    • Render the current image based on the currentIndex state.

    • Optionally display image captions or other information associated with the current image.

  4. Navigation Controls:

    • Render previous and next buttons or indicators to trigger manual navigation.

    • Update the currentIndex state based on user interaction with the controls.

    • Handle edge cases (going beyond first or last image).

Code

import React, { useState, useEffect } from 'react';

const ImageCarousel = ({ images, autoplaySpeed = 3000 }) => {
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    if (autoplaySpeed) {
      const interval = setInterval(() => {
        setCurrentIndex((prevState) => (prevState + 1) % images.length);
      }, autoplaySpeed);
      return () => clearInterval(interval);
    }
  }, [images.length, autoplaySpeed]);

  const handleNextClick = () => {
    setCurrentIndex((prevState) => (prevState + 1) % images.length);
  };

  const handlePrevClick = () => {
    setCurrentIndex((prevState) => (prevState - 1 + images.length) % images.length);
  };

  const currentImage = images[currentIndex];

  return (
    <div className="image-carousel">
      <img src={currentImage.src} alt={currentImage.alt} />
      {currentImage.caption && <p className="caption">{currentImage.caption}</p>}
      <div className="navigation">
        <button onClick={handlePrevClick}>Prev</button>
        <button onClick={handleNextClick}>Next</button>
      </div>
      {images.length > 1 && (
        <ul className="indicators">
          {images.map((image, index) => (
            <li
              key={image.src}
              className={`indicator ${currentIndex === index && 'active'}`}
              onClick={() => setCurrentIndex(index)}
            />
          ))}
        </ul>
      )}
    </div>
  );
};

export default ImageCarousel;

Explanation

  1. State Management: currentIndex tracks the currently displayed image.

  2. Automatic Slideshow (optional): useEffect with autoplaySpeed updates currentIndex periodically.

  3. Image Display and Rendering: Renders the current image and caption based on currentIndex.

  4. Navigation Controls: Buttons update currentIndex, handling edge cases.

  5. Accessibility: Indicators use aria-current and buttons have appropriate labels.

  6. Responsive Design: Utilize CSS media queries to adjust layout for different screen sizes.

Additional Notes

  • This is a basic example and can be extended with features like animation effects, thumbnails, and responsive styling.

  • Consider accessibility further by including screen reader descriptions and keyboard navigation for indicators.

Last updated