# Add to cart

> 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.

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.

## Install

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

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

- npm: none
- Hairline UI components it needs (the CLI installs them too): none
- Docs and live preview: https://hairlineui.com/ui/add-to-cart
- Registry item (source): https://hairlineui.com/r/add-to-cart.json

## 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.

```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

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `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` | `number` | `fits the cart, 44 to 72` | The print's longer side in flight, in px. |
| `options.rim` | `number` | `0.38` | Where the cart's opening is, as a share of its height from the top; the print drops in below this line. |
| `options.sound` | `boolean` | `false` | A soft knock as it lands, synthesised with Web Audio (no files). |

## 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.

## What it handles

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.

- **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.
- **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.
- **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.
- **Repeat adds stack**: Throws are independent and each dip adds to the last, so fast taps never cancel each other.
- **Follows the page**: Both ends are tracked every frame, so scrolling during the throw still lands it in the cart.

## Replaces

fly to cart animation, add to cart animation library, framer-motion layoutId, cart badge bounce

## Where it fits

- **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.

## Notes

- 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.

License: MIT (https://hairlineui.com/license#components)
