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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Modular arithmetic gives you index wrapping without special-casing the first and last slides.
- 2Wrapping navigation handlers in useCallback keeps effect cleanups stable so listeners aren't re-bound every render.
- 3One piece of state can drive multiple input methods — keyboard, swipe, and clicks — when they all funnel through shared setters.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-wrap-around-carousel-in-react-explained-javascript-ccb9/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.