Skip to main content

image-carousel

Certainly! Let's start by creating a simple React TypeScript functional component for an image carousel. This component will use hooks such as useState to manage the state and useEffect for side effects, such as setting up an interval for automatic image transitions if needed.

Here is a basic version of the component:

import React, { useState } from 'react';

type ImageCarouselProps = {
images: string[]; // Array of image URLs
interval?: number; // Time in ms for auto-transition (optional)
};

const ImageCarousel: React.FC<ImageCarouselProps> = ({ images, interval }) => {
const [currentIndex, setCurrentIndex] = useState(0);

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

const goToNext = () => {
setCurrentIndex((prevIndex) =>
prevIndex === images.length - 1 ? 0 : prevIndex + 1
);
};

return (
<div>
<button onClick={goToPrevious}>Previous</button>
<img src={images[currentIndex]} alt={`Slide ${currentIndex}`} />
<button onClick={goToNext}>Next</button>
</div>
);
};

export default ImageCarousel;

This code provides a functional image carousel component with "Previous" and "Next" buttons to navigate through the images.

Would you like to proceed with a step-by-step explanation of how this component was implemented?