Design a Photo Slider – Frontend System Design

We’ll walk through the frontend design of a horizontally scrolling image carousel — the same slider you would pull out of an Airbnb tile and reuse full-bleed on a detail page. Our goal is index state, one visible image, two prefetch slots, and controls that work with next/prev, swipe, and keyboard without wrecking CLS or stealing the page’s vertical scroll. Put simply, the task is to design a photo slider that stays fast and accessible on every input.
This is a component interview. There is no feed service and no WebSocket. Interviewers want to hear how you reserve aspect ratio, how you lazy-load, how you lock the pointer axis after 8px, and how you label slides for a screen reader. If they ask for autoplay, you mention prefers-reduced-motion and then keep this design manual.
Problem Statement
Design a horizontally scrolling image carousel.
Requirements:
- Manual next/prev, swipe, and keyboard
- Dots or a counter for position
- Works inside a card (Airbnb tile) or full-bleed
- Don’t load every image up front
This is the same slider as the Airbnb walkthrough, pulled out as its own component.
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | Autoplay? | No. Manual only. Mention prefers-reduced-motion if they ask for autoplay. |
| 2 | Loop? | Yes, optional. |
| 3 | How many images? | 1 to ~30. Design for 5–10. |
One image is a valid carousel: hide arrows and dots, still reserve the ratio. Thirty is the high end for a listing tile; if someone says a thousand, you are in a gallery virtualizer, not this component. Loop is a prop, not the default in a card (looping a 2-photo listing feels broken). Autoplay is out; if it comes back, it pauses on hover, on focus, and whenever the user prefers reduced motion.
Requirements
- Manual next/prev, swipe, and keyboard when the carousel is focused
- Dots or a numeric counter (“3 / 8”)
- Same component in a card or full-bleed — only the width changes
- Eager-load the current image; lazy-load neighbors; ignore the rest
- Optional loop
- No layout jump when the first image arrives
Non-Functional Requirements
- Aspect ratio is reserved before any byte arrives (CLS)
- Animate with
transform, notleft - A vertical page scroll must not be captured by a hesitant horizontal swipe
- Offscreen slides are
aria-hidden - Honor
prefers-reduced-motion: no slide animation, instant index change
Scalability Estimates
Scale is images on one carousel, not site traffic. Use the clarifying range.
| Metric | Estimate | Calculation | Notes |
|---|---|---|---|
| Images per carousel | 5–10 typical, 30 max | From the clarifying answer | A card on a search page may host many carousels |
| Decoded now | 3 | index ± 1 | Current plus neighbors. Ignore the rest. |
| Image weight (ballpark) | ~150–300 KB | One 1280-wide JPEG, interview guess | Not a CDN study. Use width/height + srcset. |
| First paint bytes | ~1 image | Eager current only | 10 carousels on a search page → 10 hero images, not 80 |
| Swipe lock | 8px | Existing threshold | Decide axis once, then stick |
| Loop clones | 0 or 2 | Optional: clone first/last for a seamless wrap | Or jump without clones and skip the animation |
The search-page case is the real scale talk. Fifty listing cards with ten photos each is 500 URLs. If each carousel eager-loads all ten, the page dies. If each eager-loads one and prefetches ±1 only after hover or after the card is on screen, you stay honest.
Component API
type CarouselProps = {
images: { src: string; alt: string; width: number; height: number }[];
loop?: boolean;
onIndexChange?: (index: number) => void;
};
<Carousel>
<Track> // transform: translateX(-index * 100%)
<Slide />
</Track>
<PrevButton />
<NextButton />
<Dots />
</Carousel>
Index is local state. The parent doesn’t need to know unless it’s syncing a thumbnail strip.
width and height are required so the card can reserve the ratio with aspect-ratio: width / height (or a padding hack if you must). alt is required because the slide is the content, not decoration. onIndexChange is how a parent thumbnail strip stays aligned — do not make index a fully controlled prop unless the parent has a good reason; uncontrolled with a notify is enough.
Architecture
A carousel is a viewport, a track, and a pointer controller. Keep media loading out of the buttons.
<Carousel>
IndexStore
PointerController
Prefetch
<Viewport> // overflow: hidden, aspect-ratio
<Track />
</Viewport>
<PrevButton />
<NextButton />
<Dots />
</Carousel>
Component Structure and Responsibilities
- Carousel: Owns index, loop policy, and reduced-motion. Exposes next/prev/goTo. Sets the region roles.
- Viewport: Clips the track. This is the aspect-ratio box. It is also the pointer target for swipe.
- Track: A row of slides as wide as
N * 100%. Transformed bytranslateX(-index * 100%)plus the live drag offset. - Slide: One image. Current is eager.
|i - index| === 1is lazy but eligible. The rest stay unloaded (loading="lazy"is not enough if they are in the DOM and on-screen in a long track — use a placeholder or do not setsrcuntil nearby). - PrevButton / NextButton: Named “Previous image” / “Next image”. Disabled at the ends when
loopis false. Hidden whenimages.length === 1. - Dots / Counter: Dots for ≤10, a counter for more. Each dot is a button that calls
goTo(i). The active dot isaria-current="true".
Index, Pointer, and Prefetch
No network layer in the product sense. Three small controllers:
- IndexStore:
index,goTo,next,prev. Wraps or clamps. NotifiesonIndexChange. ReadsmatchMedia('(prefers-reduced-motion: reduce)')to skip the CSS transition. - PointerController: pointerdown/move/up (and touch as pointer events). After 8px, lock axis. Horizontal → drag the track. Vertical → let the page scroll and abandon the gesture. On up, if |dx| > a threshold (say 40px or 20% of width), commit next/prev; else snap back.
- Prefetch: When index changes, or when the next button is hovered/focused, create
new Image()for neighbors. Decode ahead so the commit does not flash empty.
Move Workflow
- Mount. Reserve aspect ratio from the first image’s width/height. Set
srcon slide 0 only. - User hits next, a dot, an arrow key, or finishes a horizontal swipe.
- IndexStore computes the next index (clamp or wrap). Track transitions (or jumps if reduced motion).
- Prefetch writes
srcon index±1. Slides farther away dropsrcif you are memory-sensitive on a search page. - Live region or the slide’s accessible name updates to “3 of 8”. Offscreen slides get
aria-hidden. - If a thumbnail strip is listening,
onIndexChangefires once per committed index, not per drag pixel.
Drag is ephemeral. You do not set React index on every pointermove — you write a drag offset into a ref / transform and commit once.
Building the track

The carousel is a camera over a strip of slides. Pick one implementation and defend it.
| Transform track | Native scroll-snap | |
|---|---|---|
| How | A flex row of width: 100% slides. translate3d(-(index * 100%) + dx, 0, 0). |
The viewport is overflow-x: auto; scroll-snap-type: x mandatory. Each slide is scroll-snap-align: start. |
| Index | You own it. Buttons and keys call setIndex. |
You infer it from scrollLeft / slideWidth on scrollend. |
| Touch | You write pointer capture, rubber-band, and momentum. | The browser already does it. Better on iOS. |
| Use when | You need a controlled index, dots, and a thumbnail strip in sync. | A card slideshow where native physics matter more than control. |
Interview default: the transform track, because the index is the product (dots, counter, prefetch, Airbnb-style card). Native snap is the honest answer for a full-bleed gallery if they push you on iOS feel.
Pointer math for the transform track:
- pointerdown: store
startX,startTime, capture the pointer. Do not prevent click yet. - pointermove:
dx = clientX - startX. If|dx| > 8, mark as a swipe (so the wrapping link does not fire). Writedxinto a ref and set the transform. At the ends, rubber-band:dx = dx * 0.35so it resists. - pointerup: velocity =
dx / dt. Commit to next if|dx| > 0.3 * widthor velocity is high in that direction. Otherwise animatedxback to 0. Reduced motion: jump, do not ease.
Prefetch is a function of the committed index, not of dx. Decode is expensive; do not assign src to every slide on mount. Slide 0 has src immediately. ±1 get src after first paint or when the card is visible. Everyone else is an empty aspect-ratio box. On a search grid of 50 carousels this is the difference between a usable page and 200 image decodes.
Only the active slide is visible to AT. The others are aria-hidden. The live region says “3 of 8” on commit, not during the drag.
Card vs Full-Bleed
Same component, different chrome. In a search card, arrows appear on hover or focus (Airbnb’s pattern) so fifty tiles do not show a hundred chevrons. Dots can sit on the image. The card itself is often a link — the carousel must not swallow the click after a no-op tap, and it must swallow the click after a committed swipe.
Full-bleed on a detail page can keep arrows visible, use a counter instead of 30 dots, and pass a wider sizes. The track, index, and prefetch code do not change. If you find yourself forking the component, the split is CSS and sizes, not a second slider.
Keyboard Model
The carousel is one tab stop as a region, plus the prev/next (and maybe a counter). It is not a tab stop per slide.
- When the viewport or a control inside it is focused, ArrowLeft / ArrowRight call
prev/next. - Home / End jump to 0 and
n - 1if you want the extra, but they are optional for a card. - Space / Enter on a focused next button is the button’s own activation, not a second listener.
- Do not steal arrows while the user is focused on a search field above the grid. Focus is the gate.
Pointer and keyboard must not fight. After a keyboard move, clear any leftover dragX so the track is not sitting 12px off from a half-finished swipe.
State and Data Flow
Index is the document. Drag offset is transient UI.
- A command (button, key, committed swipe, dot) asks IndexStore for a new index.
- The track’s committed transform becomes
-index * 100%. - Prefetch reacts to index. Buttons react to index (disabled at ends).
- Pointermove, while a gesture is live, adds
dxon top of the committed transform. It does not go throughsetIndex. - Pointerup either calls
next/prevor animatesdxback to 0.
Keyboard and pointer share the same commands. If swipe calls a different code path than the next button, loop and reduced-motion will drift.
Data Model
Keep the image object the parent already has, and add the runtime pieces the carousel needs.
type CarouselImage = {
src: string;
alt: string;
width: number;
height: number;
srcSet?: string;
sizes?: string;
};
type CarouselProps = {
images: CarouselImage[];
loop?: boolean;
onIndexChange?: (index: number) => void;
};
type PointerAxis = "x" | "y" | null;
type CarouselState = {
index: number;
dragX: number;
axis: PointerAxis;
reducedMotion: boolean;
};
function neighborIndexes(index: number, n: number, loop: boolean): number[] {
const raw = [index - 1, index, index + 1];
if (loop) return raw.map((i) => (i + n) % n);
return raw.filter((i) => i >= 0 && i < n);
}
srcSet / sizes matter more on a full-bleed page than in a 300px card. The same component can pass sizes="100vw" or sizes="300px" from the parent. The carousel should not invent breakpoints.
API Design
The API is the component surface. A search page does not need a /api/carousel.
| Action | Method / Prop | Description |
|---|---|---|
| Render | <Carousel images loop> | Uncontrolled index. onIndexChange for a strip. |
| Next / prev | next() / prev() | Clamp or wrap. No-op at ends when not looping. |
| Jump | goTo(i) | Dots and thumbnails. Ignores out-of-range. |
| Prefetch | prefetch(i) | Decode i if not current. Called on hover of next. |
Example: Consuming the Carousel
function ListingCard({ photos }: { photos: CarouselImage[] }) {
return (
<article>
<Carousel
images={photos}
loop={photos.length > 2}
onIndexChange={(i) => track("listing_photo", { i })}
/>
</article>
);
}
function prefetchNeighbors(images: CarouselImage[], index: number) {
for (const i of neighborIndexes(index, images.length, true)) {
const src = images[i]?.src;
if (!src) continue;
const img = new Image();
img.src = src;
}
}
Analytics belong in onIndexChange, not inside the track transform. Firing a Mixpanel event per swipe pixel is how you invent a performance bug.
Performance
- Reserve the aspect ratio so the card doesn’t jump (CLS)
- Eager-load the current image; lazy-load index±1; ignore the rest
- Decode the next image on hover of the next button
- Animate with
transform, notleft - Use pointer events for swipe; don’t fight the vertical page scroll (lock axis after 8px)
The axis lock is the difference between a usable search page and a trapped one.
function onPointerMove(
e: PointerEvent,
startX: number,
startY: number,
axis: { current: PointerAxis },
setDrag: (x: number) => void
) {
const dx = e.clientX - startX;
const dy = e.clientY - startY;
if (axis.current === null) {
if (Math.hypot(dx, dy) < 8) return;
axis.current = Math.abs(dx) > Math.abs(dy) ? "x" : "y";
}
if (axis.current === "y") return;
e.preventDefault();
setDrag(dx);
}
function onPointerUp(dragX: number, width: number, next: () => void, prev: () => void, snap: () => void) {
const threshold = width * 0.2;
if (dragX < -threshold) next();
else if (dragX > threshold) prev();
else snap();
}
Bind pointermove on the viewport, not the window, until you have captured the pointer (setPointerCapture) so a drag that leaves the card still completes. Mark the listener as non-passive only after the axis is x, so you do not kill page scroll for every touch.
content-visibility: auto on offscreen slides is optional. Not setting src is simpler and more reliable.
Loop without a flash: if you clone slide 0 after the last slide, a next from n - 1 animates onto the clone, then on transitionend you set index = 0 with transitions disabled. The user never sees the track jump. If that feels like too much code for the interview, say you would jump without animation at the wrap. Either is better than animating the long way back through every slide.
On a search page, wrap each carousel in an IntersectionObserver and treat “card visible” as the first moment you allow ±1 prefetch. Fifty offscreen cards should hold one src each (the cover), or none if you are waiting on a windowed list.
Handling User Edge Cases
| Case | Strategy |
|---|---|
| ❌ Zero images | Render the reserved ratio with a placeholder. Hide controls. Do not mount a carousel region with no slides. |
| ❌ One image | Show the image. Hide arrows, dots, and swipe. Still expose the alt. |
| 🔄 Images array replaced | Clamp index into the new length. Prefetch again. Do not keep a now-invalid index. |
| 📶 Broken src | onError → placeholder, keep the slot so the track width does not collapse. |
| 🖱️ Accidental swipe vs click | If |dx| is tiny on pointerup, treat it as a click-through (e.g. open the listing). If you committed a slide, suppress the click. |
| ⌨️ Focus on a card | Arrow keys move slides only when the carousel (or a control inside it) is focused — not whenever the card is hovered. |
| ♿ Reduced motion | No transform transition. Index jumps. Swipe can still drag, but release snaps instantly. |
| 🔁 Loop at the ends | Either jump without animation, or use two clone slides and reset index after the transitionend so the user does not see the snap. |
Pro-Level Optimizations
| Area | Suggestion |
|---|---|
| Search pages | Do not prefetch ±1 until the card is in the viewport (IntersectionObserver) or the user hovers the card. |
| srcset | Card uses a narrow sizes. Full-bleed uses 100vw. Same images array, different sizes prop. |
| Decode | img.decode() on the neighbor, then reveal. Avoids a one-frame empty slide. |
| Memory | On a page with many carousels, drop src when |i - index| > 1 and the card leaves the viewport. |
| Click vs swipe | A didSlide flag set on commit suppresses the following click on the card link. |
| RTL | Next is visual-right. In RTL, flip the transform sign or the button meaning — pick one and keep keys consistent. |
Accessibility
- Region:
aria-roledescription="carousel",aria-label - Slides:
role="group",aria-roledescription="slide", “3 of 8” - Hide offscreen slides with
aria-hidden - Buttons have names (“Next image”), not just icons
- Arrow keys when the carousel is focused
Give the region a name from the listing (“Photos of the loft”), not “carousel”. The live update should be polite and infrequent — once per committed index, not during drag.
Dots are buttons in a list, or you use a counter and skip the extra tab stops. A 30-dot tab sequence inside a search card is hostile. Prefer a counter plus prev/next when N is large.
Do not auto-rotate. If a later prompt adds autoplay, pause it on focus, on hover, and when prefers-reduced-motion: reduce matches. The APG carousel pattern treats autoplay as an interruption.
Security
Image URLs are data. If they can be set by a host, they still render as <img src>, never as HTML. alt is user-facing text — render it as text. Do not turn a caption into markdown inside the slide.
Hotlinking and signed CDN URLs expire. A prefetch that runs minutes later can 403. Treat error as a placeholder, not a retry storm.
Library vs Custom
| Pros | Cons | |
|---|---|---|
| swiper / keen-slider | Touch, a11y, edge cases | Bundle weight |
| Custom | Tiny, exact API | You own swipe physics and a11y |
In an interview, custom is the stronger answer if you cover swipe + a11y. In production, a small slider lib is fine.
If you pick a library, say what you still own: aspect-ratio reservation, which images get src, and the card-vs-bleed sizes attribute. The library does not get those right for a search grid unless you configure them.
Interview details people skip
GFE’s carousel answer defaults to native scroll. Ours defaults to a transform track. Both are valid. Say which one you are defending and why the other exists.
Native snap is the cheaper swipe. A flex row, overflow-x: auto, scroll-snap-type: x mandatory, each slide flex: 0 0 100% and scroll-snap-align: start. Buttons and keys call slide.scrollIntoView({ behavior, block: "nearest", inline: "start" }). That avoids hard-coding slide width and it respects dir — you do not negate scrollLeft in RTL. After scroll settles (scrollend), derive index from the snapped slide. Only that settled commit fires onIndexChange(index, { source }). An interrupted swipe or a no-op at a finite boundary does not emit. Re-align the active slide after the viewport resizes.
Use the transform track when a parent thumbnail strip must stay locked to a controlled index. Use snap when iOS physics matter more than control. Do not keep both as source of truth.
Slides are <img>, not painted backgrounds. object-fit: cover or contain is a prop (per carousel or per image). A div with background-image drops alt, srcset, and native lazy-load. Reserve aspect-ratio from intrinsic width/height before any byte arrives. The first slide is eager and can take fetchpriority="high" if it is LCP. Later slides may use loading="lazy" — that is a hint, not a contract. You still own which src is set.
Preload on intent, then escalate. Airbnb’s listing tiles are the production story: load cover only; if the card stays ~50% visible for about a second, prefetch image 2; cancel if it leaves the viewport; after a swipe, prefetch the next three with ~100ms stagger. Interview baseline: current eager, ±1 on hover/focus of Next or when the card is on screen. srcset + sizes so a 300px card does not download a 1600px file.
Autoplay is a state machine if they ask for it. Idle | Running | Transitioning | PausedByUser. Focus, pointer enter, or any manual next/prev/dot/swipe stops the timer. It restarts only from a Play control, which sits before the rotating content in tab order. Reduced motion disables autoplay and the slide animation. Clear the timer on unmount. Announce user-initiated index changes politely. Keep automatic rotation quiet.
On touch, prev/next hit targets are at least 44px — the whole left/right strip is fair game. Dots are too small to tap; hide them or make them non-interactive and keep a counter. Zero or one image: hide chrome and autoplay.
Conclusion: How to Design a Photo Slider
A carousel is index state, one visible image, and two prefetch slots. Everything else is accessibility and not wrecking CLS.
The senior half is gesture and loading policy. Lock the pointer axis after 8px so the page can still scroll. Animate transform. Eager-load the current photo, decode ±1, and leave the other twenty alone — especially when fifty cards share the page. Hide controls when N is 1. Jump, don’t animate, when the user asks for reduced motion.
Keep the public API to images, optional loop, and onIndexChange. Put swipe, prefetch, and roles inside the component so every listing tile does not reimplement them. That is the design.
