Sign up and get 15% off the four courses and Lifetime.

Expand gallery

A row of project pictures: the one you point at opens wide and the others fold into slim strips with their names on their side. Good for a selected work strip on a home page.

Free·React and Tailwind

Try it

How to use this

  1. 01

    Make a file called expand-gallery.tsx in your project's components folder.

  2. 02

    Install what it needs: npm install framer-motion

  3. 03

    Paste the code in, keeping the licence note at the top.

  4. 04

    Import it where you want it and change the words, colours and sizes to yours.

The code

expand-gallery.tsx
/**
 * MIT License
 *
 * Copyright (c) 2024 Eduardo Calvo
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
"use client";

import { motion, useReducedMotion } from "framer-motion";
import { type KeyboardEvent, useEffect, useRef, useState } from "react";

const cn = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");

export type ExpandGalleryOrientation = "horizontal" | "vertical";

export interface ExpandGalleryItem {
  id: string;
  title: string;
  image?: string;
  alt?: string;
  description?: string;
}

export interface ExpandGalleryProps {
  items: ExpandGalleryItem[];
  orientation?: ExpandGalleryOrientation;
  /** Controlled open panel. Pair it with `onActiveIndexChange`. */
  activeIndex?: number;
  onActiveIndexChange?: (index: number) => void;
  /** How much wider the open panel grows than the closed ones. */
  expandedFlex?: number;
  collapsedFlex?: number;
  /** Keep the titles on closed panels, turned on their side. */
  showLabelsWhenCollapsed?: boolean;
  /** Smaller type and padding, for tight spaces. */
  compact?: boolean;
  className?: string;
}

const SPRING = { bounce: 0.1, duration: 0.3, type: "spring" } as const;
const INSTANT = { duration: 0 } as const;

/**
 * A row of picture panels. The one under the pointer (or tapped, or focused) opens wide and
 * the rest fold into slim strips with their titles turned on their side.
 */
export function ExpandGallery({
  items,
  orientation = "horizontal",
  activeIndex: activeIndexProp,
  onActiveIndexChange,
  expandedFlex = 4,
  collapsedFlex = 1,
  showLabelsWhenCollapsed = true,
  compact = false,
  className,
}: ExpandGalleryProps) {
  const shouldReduceMotion = useReducedMotion();
  const [internalActive, setInternalActive] = useState(0);
  const isControlled = activeIndexProp !== undefined;
  const activeIndex = isControlled ? activeIndexProp : internalActive;
  const [isHoverDevice, setIsHoverDevice] = useState(false);
  const panelRefs = useRef<(HTMLButtonElement | null)[]>([]);
  const isHorizontal = orientation === "horizontal";

  useEffect(() => {
    const mediaQuery = window.matchMedia("(hover: hover) and (pointer: fine)");
    setIsHoverDevice(mediaQuery.matches);
    const handleChange = (event: MediaQueryListEvent) => setIsHoverDevice(event.matches);
    mediaQuery.addEventListener("change", handleChange);
    return () => mediaQuery.removeEventListener("change", handleChange);
  }, []);

  const setActive = (index: number) => {
    if (!isControlled) setInternalActive(index);
    onActiveIndexChange?.(index);
  };

  const handleKeyDown = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
    const nextKey = isHorizontal ? "ArrowRight" : "ArrowDown";
    const prevKey = isHorizontal ? "ArrowLeft" : "ArrowUp";
    if (event.key === nextKey) {
      event.preventDefault();
      const next = Math.min(index + 1, items.length - 1);
      setActive(next);
      panelRefs.current[next]?.focus();
    } else if (event.key === prevKey) {
      event.preventDefault();
      const prev = Math.max(index - 1, 0);
      setActive(prev);
      panelRefs.current[prev]?.focus();
    }
  };

  return (
    <div
      aria-label="Picture panels"
      role="group"
      className={cn("flex w-full", compact ? "gap-1.5" : "gap-2", isHorizontal ? "h-[360px] flex-row" : "h-[520px] flex-col", className)}
    >
      {items.map((item, index) => {
        const isActive = index === activeIndex;
        const showLabel = isActive || showLabelsWhenCollapsed;
        const turned = isHorizontal && !isActive;
        return (
          <motion.button
            key={item.id}
            ref={(el) => {
              panelRefs.current[index] = el;
            }}
            type="button"
            aria-label={item.title}
            aria-pressed={isActive}
            initial={false}
            animate={{ flexGrow: isActive ? expandedFlex : collapsedFlex }}
            transition={shouldReduceMotion ? INSTANT : SPRING}
            style={{ flexBasis: 0 }}
            onClick={() => setActive(index)}
            onFocus={() => setActive(index)}
            onKeyDown={(event) => handleKeyDown(event, index)}
            onMouseEnter={() => {
              if (isHoverDevice) setActive(index);
            }}
            className={cn(
              "relative min-h-0 min-w-0 flex-1 overflow-hidden border border-black/10 bg-[#e7e9ff] text-left outline-none focus-visible:ring-2 focus-visible:ring-[#2f3cff] focus-visible:ring-offset-2",
              compact ? "rounded-lg" : "rounded-2xl",
            )}
          >
            {item.image ? (
              <img
                src={item.image}
                alt={item.alt ?? item.title}
                draggable={false}
                className="absolute inset-0 h-full w-full object-cover"
              />
            ) : null}
            <div aria-hidden="true" className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/10 to-transparent" />
            <motion.div
              initial={false}
              animate={{ opacity: showLabel ? 1 : 0 }}
              transition={shouldReduceMotion ? INSTANT : SPRING}
              className={cn(
                "absolute inset-x-0 bottom-0",
                compact ? "p-2" : "p-4",
                turned && "flex h-full items-end justify-center",
              )}
            >
              {turned ? (
                <p
                  className={cn("whitespace-nowrap font-medium text-white [writing-mode:vertical-rl] rotate-180", compact ? "text-[10px]" : "text-sm")}
                >
                  {item.title}
                </p>
              ) : (
                <div>
                  <p className={cn("font-semibold text-white", compact ? "text-xs" : "text-base")}>{item.title}</p>
                  {item.description ? (
                    <p className={cn("mt-1 text-white/80", compact ? "text-[10px] leading-snug" : "text-sm")}>{item.description}</p>
                  ) : null}
                </div>
              )}
            </motion.div>
          </motion.button>
        );
      })}
    </div>
  );
}
NextImage strip