Try 'magnetic button'
View code

Specification

Catalogue
No. 12 of 110
Section
Tabs
Interaction
Drag, Layout Animation
Element
Tabs
Preview
Live component
Imports
react 19.3.1, @number-flow/react 0.6.2
Added

Notes

One marker follows the pointer along the tabs, and on a phone the panel swipes to the next tab.

The eye follows a single moving marker, and the new panel comes in from the side you moved toward, so it is clear where you went.

Marker glides 250ms on --ease-glide to the hovered tab, back to the chosen one on leave. Panel enters 20px from the side moved toward, 250ms. Swipe of 50px or more, mostly sideways, changes tab; vertical scrolling still works. Height glides between panels (the same mechanism as Height that glides).

The names, figures and pictures in the demo are sample content; a real build uses the client's own.

Code

React and plain CSS
"use client";

import { useId, useLayoutEffect, useRef, useState, type PointerEvent } from "react";
import { AutoHeight } from "@/components/pieces/motion-helpers";
import { tabKey } from "@/components/pieces/shared";
import type { LivePreviewProps } from "@/components/live/types";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./smooth-tab.css";

const AUDIENCES = [
  { id: "homes", label: "Homes", title: "Regular home cleans", body: ["Weekly or fortnightly, same cleaner each time.", "Bring your own products or use ours."] },
  { id: "lets", label: "Landlords", title: "End of tenancy", body: ["A full clean between tenants, checked against the inventory.", "Oven, fridge and carpets included.", "Photos of every room when we finish."] },
  { id: "offices", label: "Offices", title: "Small offices", body: ["Early morning or evening, so the team is never in the way."] },
];

function SmoothTabDemo() {
  const [sel, setSel] = useState(0);
  const [hover, setHover] = useState<number | null>(null);
  const [dir, setDir] = useState<"left" | "right">("right");
  const [pill, setPill] = useState<{ left: number; width: number } | null>(null);
  const tabs = useRef<(HTMLButtonElement | null)[]>([]);
  const swipe = useRef<{ x: number; y: number; id: number } | null>(null);
  const uid = useId();
  const target = hover ?? sel;

  useLayoutEffect(() => {
    const el = tabs.current[target];
    if (el) setPill({ left: el.offsetLeft, width: el.offsetWidth });
  }, [target]);

  const choose = (i: number, focus = false) => {
    if (i === sel) return;
    setDir(i > sel ? "right" : "left");
    setSel(i);
    if (focus) tabs.current[i]?.focus();
  };
  const onDown = (e: PointerEvent<HTMLDivElement>) => {
    if (e.pointerType !== "mouse") swipe.current = { x: e.clientX, y: e.clientY, id: e.pointerId };
  };
  const onUp = (e: PointerEvent<HTMLDivElement>) => {
    const s = swipe.current;
    swipe.current = null;
    if (!s || s.id !== e.pointerId) return;
    const dx = e.clientX - s.x;
    if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(e.clientY - s.y) * 1.5) choose(Math.min(AUDIENCES.length - 1, Math.max(0, sel + (dx < 0 ? 1 : -1))));
  };
  const a = AUDIENCES[sel]!;

  return (
    <div className="dm">
      <div className="stab">
        <div className="stab-list" role="tablist" aria-label="Who it is for" onPointerLeave={() => setHover(null)}>
          {pill && <span className="stab-pill" style={{ translate: `${pill.left}px 0`, width: pill.width }} aria-hidden="true" />}
          {AUDIENCES.map((x, i) => (
            <button
              key={x.id}
              ref={(el) => {
                tabs.current[i] = el;
              }}
              id={`${uid}-t${i}`}
              type="button"
              role="tab"
              aria-selected={sel === i}
              aria-controls={`${uid}-p`}
              tabIndex={sel === i ? 0 : -1}
              onClick={() => choose(i)}
              onPointerEnter={(e) => {
                if (e.pointerType === "mouse") setHover(i);
              }}
              onKeyDown={(e) => {
                const n = tabKey(e.key, i, AUDIENCES.length);
                if (n !== null) {
                  e.preventDefault();
                  choose(n, true);
                }
              }}
            >
              {x.label}
            </button>
          ))}
        </div>
        <AutoHeight>
          <div className="stab-panel" id={`${uid}-p`} role="tabpanel" aria-labelledby={`${uid}-t${sel}`} tabIndex={0} onPointerDown={onDown} onPointerUp={onUp} onPointerCancel={() => (swipe.current = null)}>
            <div key={a.id} className="stab-body" data-dir={dir}>
              <h3>{a.title}</h3>
              <ul>
                {a.body.map((l) => (
                  <li key={l}>{l}</li>
                ))}
              </ul>
            </div>
          </div>
        </AutoHeight>
        <p className="dm-hint">Swipe the panel on a phone, or use the arrow keys</p>
      </div>
    </div>
  );
}

// What a hovered card shows: the piece used the way a visitor would.
const TOUR: Tour = [
  { click: '[role="tab"]', nth: 1 },
  { click: '[role="tab"]', nth: 2 },
  { click: '[role="tab"]', nth: 0 },
];

export default function SmoothTabEntry(props: LivePreviewProps) {
  return (
    <PieceStage {...props} label="Tabs you can swipe" sample tour={TOUR}>
      <SmoothTabDemo />
    </PieceStage>
  );
}

More like this

One question at a time

Layout AnimationForms and inputs

Video poster that opens the player

Press, Layout AnimationMedia and galleries

Menu that opens into link cards

Press, Layout AnimationNavigation

Cookie choice that folds away

FeedbackOverlays and toasts

Steps that scroll past a picture that holds

ScrollPage sections

Comparison bars

Layout AnimationCharts and numbers