Skip to main content

Carousel

Carousel.tsx
import React, { useState } from 'react';
import styles from './Carousel.module.css';

interface CarouselProps {
images: string[];
}

const Carousel = ({ images }: CarouselProps) => {
const [activeIndex, setActiveIndex] = useState(0);

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

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

return (
<div className={styles.carousel}>
<button className={styles.prevButton} onClick={handlePrevClick}>
Prev
</button>
<div className={styles.imageContainer}>
<img className={styles.image} src={images[activeIndex]} alt={`Image ${activeIndex}`} />
</div>
<button className={styles.nextButton} onClick={handleNextClick}>
Next
</button>
</div>
);
};

export default Carousel;


Carousel.module.css
.carousel {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
padding: 16px;
background-color: #f1f1f1;
}

.imageContainer {
height: 200px;
width: 400px;
display: flex;
align-items: center;
justify-content: center;
}

.image {
height: 100%;
max-width: 100%;
object-fit: contain;
}

.prevButton,
.nextButton {
background-color: #333;
color: #fff;
border: none;
padding: 8px 16px;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
}

.prevButton:hover,
.nextButton:hover {
opacity: 0.8;
}

.prevButton {
margin-right: 16px;
}

.nextButton {
margin-left: 16px;
}