Cart

Change item quantities or remove items from the cart. The subtotal, shipping, and total are calculated automatically from the contents.

This code is made of 1 file.

CartPage.tsx

Cart page

How to use (Next.js)

Three steps to show this screen in your own project

  1. 1

    Install the components and libraries in your terminal (once)

    npx shadcn@latest add button
    npm i lucide-react

    If your project doesn’t have shadcn/ui yet, run npx shadcn@latest init first

  2. 2

    Paste the files here

    my-app/
    ├─ components/
    │   └─ cart/
    │       └─ CartPage.tsx   ← copied from the window above
    └─ app/
        └─ cart/
            └─ page.tsx   ← created in step 3

    Create any folders that don’t exist.

  3. 3

    Import it in a page file

    import CartPage from "@/components/cart/CartPage"
    
    export default function Page() {
      return <CartPage />
    }

    Write this in app/cart/page.tsx. Run npm run dev and open /cart to see it

Key points

  1. 1

    Update or remove just one item in a list

    To change a quantity, use map to build a list where only that item’s quantity changes. To remove an item, use filter to keep everything except that item. Never modify the original list directly.

  2. 2

    Calculate totals every time instead of storing them

    Don’t keep the subtotal, shipping, or total in state — calculate them from the cart contents on every render. Change the contents and the totals stay correct automatically (storing them is how they get out of sync).

  3. 3

    Have a screen for the empty state

    When everything is removed, show “Your cart is empty”. An empty list next to a $0 total looks broken.

Tools used

Click to see the comparison in Part 2