javascript 69 lines · 9 steps

Building a wrap-around Carousel in React

A React image carousel that navigates by keyboard, swipe, and clicks while wrapping cleanly at both ends.

Explained by highlit
1import { useState, useEffect, useRef, useCallback } from 'react';
2 
3export default function Carousel({ images }) {
4 const [index, setIndex] = useState(0);
5 const touchStart = useRef(null);
6 
7 const clamp = useCallback(
8 (next) => (next + images.length) % images.length,
9 [images.length]
10 );
11 
12 const goTo = useCallback((next) => setIndex((i) => clamp(typeof next === 'function' ? next(i) : next)), [clamp]);
13 const prev = useCallback(() => goTo((i) => i - 1), [goTo]);
14 const next = useCallback(() => goTo((i) => i + 1), [goTo]);
15 
16 useEffect(() => {
17 const onKey = (e) => {
18 if (e.key === 'ArrowLeft') prev();
19 else if (e.key === 'ArrowRight') next();
20 };
21 window.addEventListener('keydown', onKey);
22 return () => window.removeEventListener('keydown', onKey);
23 }, [prev, next]);
24 
25 const handleTouchStart = (e) => {
26 touchStart.current = e.touches[0].clientX;
27 };
28 
29 const handleTouchEnd = (e) => {
30 if (touchStart.current == null) return;
31 const delta = e.changedTouches[0].clientX - touchStart.current;
32 if (Math.abs(delta) > 50) (delta < 0 ? next : prev)();
33 touchStart.current = null;
34 };
35 
36 return (
37 <div
38 className="carousel"
39 role="region"
40 aria-roledescription="carousel"
41 onTouchStart={handleTouchStart}
42 onTouchEnd={handleTouchEnd}
43 >
44 <button className="carousel__nav carousel__nav--prev" onClick={prev} aria-label="Previous slide">
45
46 </button>
47 
48 <div className="carousel__viewport">
49 <img src={images[index].src} alt={images[index].alt} className="carousel__image" draggable={false} />
50 </div>
51 
52 <button className="carousel__nav carousel__nav--next" onClick={next} aria-label="Next slide">
53
54 </button>
55 
56 <div className="carousel__dots">
57 {images.map((img, i) => (
58 <button
59 key={img.src}
60 className={`carousel__dot${i === index ? ' is-active' : ''}`}
61 onClick={() => goTo(i)}
62 aria-label={`Go to slide ${i + 1}`}
63 aria-current={i === index}
64 />
65 ))}
66 </div>
67 </div>
68 );
69}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Modular arithmetic gives you index wrapping without special-casing the first and last slides.
  2. 2Wrapping navigation handlers in useCallback keeps effect cleanups stable so listeners aren't re-bound every render.
  3. 3One piece of state can drive multiple input methods — keyboard, swipe, and clicks — when they all funnel through shared setters.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a wrap-around Carousel in React — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code