Skip to content
Browse documentation

One call throws the product into the cart on a real arc; it drops in below the rim and the cart dips with the weight.

Used forProduct pageProduct gridSaved and collectionsPlaylists

Install with the shadcn CLI

$ npx shadcn@latest add https://hairlineui.com/r/add-to-cart.json

Registered the namespace? Then it’s shadcn add @hairline/add-to-cart. Set it up

Templates

Need the whole page?

61 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 6 are free.

All 61 templates

Where it’s used

  • Product page

    Add to cart from the buy box, thrown into the cart in the header.

  • Product grid

    Quick add from a card in a listing; repeat adds stack in the cart.

  • Saved and collections

    Save a photo or a post into a collection or a folder in the sidebar.

  • Playlists

    Add a track or a video to a queue or a playlist button.

What it handles for you

After "Add to cart" people look for proof it went in. A badge that changes somewhere else is easy to miss; a flying image usually needs an animation library and drifts off when the page scrolls.

Instead of wiring upfly to cart animationadd to cart animation libraryframer-motion layoutIdcart badge bounce
  1. One call, any two elements

    throwToCart(source, target) works with whatever you pass: an image, a card, a row, and any cart, folder or playlist button.

  2. Lands on time

    The promise resolves as the print disappears into the cart, while it is still dipping, so your count, badge or toast changes as it lands, not before. A slow render then can never freeze the print mid-drop.

  3. A real throw

    A parabola with even sideways speed, a lean that follows the speed, a drop below the rim and a sprung dip in the direction it was hit.

  4. Repeat adds stack

    Throws are independent and each dip adds to the last, so fast taps never cancel each other.

  5. Follows the page

    Both ends are tracked every frame, so scrolling during the throw still lands it in the cart.

Overview

An add-to-cart that is one line in your own code. Call throwToCart with the product image and the cart button: a copy of the image lifts off as a small rounded print and is tossed on a real arc, even sideways speed and gravity on the way down, leaning with its speed. Over the cart it drops in below the rim, the way something drops into a bag, and the cart takes the weight: it dips the way it was hit and springs back. The promise resolves as the print disappears into it, while the cart is still dipping, so your count goes up as the item lands. The product stays where it is, and your cart, badge and API stay yours.

States

lift
A copy of the source shrinks to a small rounded print (44 to 72px, sized to the cart) and rises a touch, starting on its way before it has finished shrinking.
throw
It flies on a parabola peaking above the higher end, leaning up as it rises and tipping over as it falls: 0.68 to 1 second, by distance.
drop in
Once it is coming down above the cart, the cart's rim hides what passes below it, so the print drops in; the cart dips along the throw and springs back, and the promise resolves once the print is all the way in.
reduced motion
No throw: the promise resolves at once and your count changes in place.

Usage

usage.tsx
import { throwToCart } from "@/components/add-to-cart";<button  onClick={async () => {    await throwToCart(imageRef.current, cartRef.current);    setCount((n) => n + 1);  }}>  Add to cart</button>

With your cart API

Start the request and the throw together, and count the item when it lands. If the request fails, take it back out and say so.

example.tsx
"use client";import * as React from "react";import { throwToCart } from "@/components/add-to-cart";export function AddButton({ productId, image, cart, onAdded }: {  productId: string;  image: React.RefObject<HTMLElement | null>;  cart: React.RefObject<HTMLElement | null>;  onAdded: (count: number) => void;}) {  const [error, setError] = React.useState("");  async function add() {    setError("");    const request = fetch("/api/cart", { method: "POST", body: JSON.stringify({ productId }) });    await throwToCart(image.current, cart.current, { sound: true });    const res = await request;    if (!res.ok) return setError("Couldn't add it. Try again.");    const { count } = await res.json();    onAdded(count);  }  return (    <>      <button onClick={add}>Add to cart</button>      {error && <p role="alert">{error}</p>}    </>  );}

Props

throwToCart(source, target, options?)
Promise<void>
Throws a copy of source into target. Resolves when it drops in (at once under reduced motion, or if either element is missing).
options.size= fits the cart, 44 to 72
number
The print's longer side in flight, in px.
options.rim= 0.38
number
Where the cart's opening is, as a share of its height from the top; the print drops in below this line.
options.sound= false
boolean
A soft knock as it lands, synthesised with Web Audio (no files).

Accessibility and motion

  • The print is a copy of the source made when you call it, drawn in a layer over the page; the source itself is never moved or hidden.
  • Only transforms and one clip change while it flies; the copy is removed once it has dropped in.
  • The dip is a Web Animations transform added on top of the cart's own (composite: add), so it never fights your styles or hover states.
  • Announce the change for screen readers where you keep the count, e.g. aria-label="Cart, 3 items" on the cart button.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

Source

"use client";/* ───────────────────────────────────────────────────────── * ADD TO CART: throw it in * * One call: `await throwToCart(productImage, cartButton)`. A * copy of the image lifts off as a small rounded print and is * tossed on a real arc (even sideways speed, gravity on the way * down), tilting with its speed. Over the cart it drops in * below the rim, as into a bag, and the cart takes the weight: * it dips the way it was hit and springs back. The promise * resolves as the print disappears into it, while the cart is * still dipping, so your count goes up as the item lands. * * Your page is untouched: the product stays where it is, the * cart's state and badge are yours, and quick repeat throws * just stack (each dip adds to the last). Works for anything * thrown somewhere: save to a collection, add to a playlist, * move to a folder. * ───────────────────────────────────────────────────────── */import { springFrames } from "./ui-interaction-motion";import { playSound } from "./ui-sounds";export interface ThrowToCartOptions {  /** Size of the print in flight, on its longer side, in px. Default: fits the cart, between 44 and 72. */  size?: number;  /** Where the cart's opening is, as a share of its height from the top. The print drops in below this line. */  rim?: number;  /** Play a soft knock when it lands (synthesised, no files). */  sound?: boolean;}type Point = { x: number; y: number };const clamp = (n: number, lo: number, hi: number) => (n < lo ? lo : n > hi ? hi : n);const easeOut = (t: number) => 1 - (1 - clamp(t, 0, 1)) ** 3;const lerp = (a: number, b: number, t: number) => a + (b - a) * t;let layer: HTMLDivElement | null = null;function topLayer() {  if (layer && layer.isConnected) return layer;  layer = document.createElement("div");  layer.setAttribute("aria-hidden", "true");  layer.style.cssText = "position:fixed;inset:0;pointer-events:none;z-index:2147483000;contain:layout style;";  document.body.appendChild(layer);  return layer;}function reducedMotion() {  return !!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;}/** The cart takes the weight: a dip along the throw's direction that springs back, added to whatever else it's doing. */function dip(target: HTMLElement, direction: Point) {  const length = Math.hypot(direction.x, direction.y) || 1;  const dx = (direction.x / length) * 0.45, dy = Math.max(0.55, direction.y / length);  const frames = springFrames(0, 0, 0.13, 760, { omega: 19, damping: 0.4, steps: 48 });  target.animate(    frames.map(({ value, offset }) => ({      offset,      transform: `translate(${(value * dx).toFixed(2)}px, ${(value * dy).toFixed(2)}px) scale(${(1 - value * 0.012).toFixed(4)}, ${(1 - value * 0.016).toFixed(4)})`,    })),    { duration: 760, composite: "add" },  );}/** * Throws a copy of `source` (a product image, a card) into `target` (the cart button). Resolves when it lands in the * cart; update your count then. */export function throwToCart(source: HTMLElement | null | undefined, target: HTMLElement | null | undefined, options: ThrowToCartOptions = {}): Promise<void> {  if (!source || !target || typeof window === "undefined" || reducedMotion()) return Promise.resolve();  const S = source.getBoundingClientRect();  const T0 = target.getBoundingClientRect();  const rimShare = options.rim ?? 0.38;  const W = source.offsetWidth || S.width, H = source.offsetHeight || S.height;  const long = Math.max(W, H);  const print = options.size ?? clamp(Math.min(T0.width, T0.height) * 1.5, 44, 72);  const small = print / long; // scale of the print in flight  const sx = window.scrollX, sy = window.scrollY;  const computed = getComputedStyle(source);  const corner = parseFloat(computed.borderTopLeftRadius) || 0;  // The print: a copy of the element, kept at its own size and scaled, so it stays sharp at every step.  const clip = document.createElement("div"); // a full-screen window whose bottom is the cart's rim, once it's dropping in  clip.style.cssText = "position:absolute;inset:0;";  const card = document.createElement("div");  card.style.cssText = `position:absolute;left:0;top:0;width:${W}px;height:${H}px;overflow:hidden;transform-origin:50% 50%;will-change:transform;`;  const copy = source.cloneNode(true) as HTMLElement;  copy.removeAttribute("id");  copy.querySelectorAll("[id]").forEach((n) => n.removeAttribute("id"));  copy.setAttribute("inert", "");  copy.style.cssText += ";position:absolute;inset:0;width:100%;height:100%;margin:0;transform:none;translate:none;scale:none;rotate:none;opacity:1;visibility:visible;animation:none;transition:none;";  const edge = document.createElement("div");  edge.style.cssText = "position:absolute;inset:0;border-radius:inherit;pointer-events:none;";  card.append(copy, edge);  clip.appendChild(card);  topLayer().appendChild(clip);  const start: Point = { x: S.left + S.width / 2, y: S.top + S.height / 2 };  const distance = Math.hypot(T0.left + T0.width / 2 - start.x, T0.top + T0.height / 2 - start.y);  const total = clamp(600 + distance * 0.42, 680, 1000);  const shrinkEnd = 0.36 * total; // the print comes off the page...  const flyStart = 0.16 * total; // ...and is already on its way before it's done  return new Promise<void>((resolve) => {    const began = performance.now();    let caught = false, dropping = false, last: Point | null = null, angle = 0;    const frame = (now: number) => {      const t = now - began;      // Everything follows the page: the throw starts where the product is now and lands where the cart is now.      const T = target.getBoundingClientRect();      const ox = sx - window.scrollX, oy = sy - window.scrollY;      const lift = easeOut(t / shrinkEnd);      const from: Point = { x: start.x + ox, y: start.y + oy - 12 * lift };      const rimY = T.top + T.height * rimShare;      const landScale = small * clamp((T.width * 0.7) / print, 0.45, 1);      const to: Point = { x: T.left + T.width / 2, y: rimY + (H * landScale) * 0.62 };      // A projectile: a parabola with even sideways speed, peaking just above the higher end, so it stays on screen even      // when the cart sits at the top of the page.      const apex = Math.min(from.y, to.y) - clamp(Math.abs(to.x - from.x) * 0.12 + 22, 28, 72);      const control: Point = { x: (from.x + to.x) / 2, y: 2 * apex - (from.y + to.y) / 2 };      const u = clamp((t - flyStart) / (total - flyStart), 0, 1);      const pos: Point = {        x: (1 - u) ** 2 * from.x + 2 * (1 - u) * u * control.x + u * u * to.x,        y: (1 - u) ** 2 * from.y + 2 * (1 - u) * u * control.y + u * u * to.y,      };      const scale = lerp(lerp(1, small, lift), landScale, easeOut((u - 0.45) / 0.55));      // The print leans with its speed: nose up as it rises, tipping over as it falls.      if (last) {        const vx = pos.x - last.x, vy = pos.y - last.y;        if (Math.hypot(vx, vy) > 0.4) {          const heading = (Math.atan2(vy, Math.abs(vx) + 0.001) * 180) / Math.PI;          angle = lerp(angle, clamp(heading * 0.32 * Math.sign(to.x - from.x || 1), -24, 24), 0.35);          // No lean while it is still big over the product: only once it has come off as a print.        }      }      const lean = angle * lift * lift;      const s = Math.max(scale, 0.01);      card.style.borderRadius = `${(lerp(corner, Math.min(10, print * 0.18), lift) / s).toFixed(2)}px`;      // A thin paper edge, like a photo print, so it reads as an object, not a hole in the page.      edge.style.boxShadow = `inset 0 0 0 ${((2 * lift) / s).toFixed(2)}px rgb(255 255 255 / 0.92)`;      card.style.transform = `translate3d(${(pos.x - W / 2).toFixed(2)}px, ${(pos.y - H / 2).toFixed(2)}px, 0) rotate(${lean.toFixed(2)}deg) scale(${scale.toFixed(4)})`;      // On the way down, once the whole print is above the cart's rim, the rim starts hiding what passes below it.      const descending = last !== null && pos.y > last.y;      if (!dropping && descending && pos.y + (H * scale) / 2 < rimY && u > 0.5) dropping = true;      if (dropping) clip.style.clipPath = `inset(0 0 ${Math.max(0, window.innerHeight - rimY).toFixed(2)}px 0)`;      if (!caught && (dropping || u > 0.9) && pos.y >= rimY) {        caught = true;        if (options.sound) playSound("drop", 0.45);        dip(target, { x: to.x - control.x, y: to.y - control.y });      }      last = pos;      if (u < 1) {        requestAnimationFrame(frame);        return;      }      clip.remove();      if (layer && !layer.childElementCount) {        layer.remove();        layer = null;      }      // Resolve once it is all the way in, with the dip already playing, so whatever your app renders next can never      // freeze a half-sunk print on screen.      resolve();    };    requestAnimationFrame(frame);  });}

Registry item: /r/add-to-cart.json