How to Create a Simple Carousel/Slider in React
Source: Dev.to
Carousel Component
A carousel (or slider) is a great way to display a series of images or content, one at a time. You can use buttons to navigate through them. Below is a simple implementation using React.
import { useEffect, useState } from 'react';
import { shortList, list, longList } from '../data';
import { FaQuoteRight } from 'react-icons/fa';
import { FiChevronLeft, FiChevronRight } from 'react-icons/fi';
const Carousel = () => {
const [people, setPeople] = useState(longList);
const [currentPersonIndex, setCurrentPersonIndex] = useState(0);
const prevSlide = () => {
setCurrentPersonIndex((oldIndex) => {
const newIndex = (oldIndex - 1 + people.length) % people.length;
return newIndex;
});
};
const nextSlide = () => {
setCurrentPersonIndex((oldIndex) => {
const newIndex = (oldIndex + 1) % people.length;
return newIndex;
});
};
useEffect(() => {
const sliderId = setInterval(() => {
nextSlide();
}, 2000);
return () => {
clearInterval(sliderId);
};
}, [currentPersonIndex]);
return (
{people.map((person, personIndex) => {
const { id, name, image, title, quote } = person;
return (
<div key={id}>
<h3>{name}</h3>
<p>{title}</p>
<p>{quote}</p>
</div>
);
})}
);
};
export default Carousel;
Explanation of the Functions: nextSlide and prevSlide
nextSlide Function
const nextSlide = () => {
setCurrentPersonIndex((oldIndex) => {
const newIndex = (oldIndex + 1) % people.length;
return newIndex;
});
};
How it works
- Reads the current index (
currentPersonIndex). - Adds 1 to move to the next item.
- The modulo operator (
% people.length) wraps the index back to 0 when it reaches the end of the list, creating a continuous loop.
Example
If currentPersonIndex is 4 (the last person) and the list has 5 items, (4 + 1) % 5 results in 0, so the carousel returns to the first person.
prevSlide Function
const prevSlide = () => {
setCurrentPersonIndex((oldIndex) => {
const newIndex = (oldIndex - 1 + people.length) % people.length;
return newIndex;
});
};
How it works
- Reads the current index.
- Subtracts 1 to move to the previous item.
- Adding
people.lengthbefore applying the modulo ensures the result stays positive, wrapping from the first item to the last.
Example
If currentPersonIndex is 0 (the first person) and the list has 5 items, (-1 + 5) % 5 yields 4, moving the carousel to the last person.
Key Points to Remember
- The expression
% people.lengthenables the carousel to wrap around both forward and backward. nextSlideincrements the index;prevSlidedecrements it.- Updating
currentPersonIndextriggers a re‑render, showing the appropriate slide.