geekskai Logogeekskai
ToolsBlogPricing
Sign in
Sign in
ToolsBlogSign in
Thursday, February 13, 2025|6.42Mins Read

Build a React Swag Shop: Shared Cart State and Quantity Validation

Authors
  • avatar
    Name
    Geeks Kai
    Twitter
    @KaiGeeks
Discuss on Twitter • View on GitHub

Tags

reacte-commerceweb-developmentjavascriptonline-shop

Previous Article

Utilizing NavLink for State Passing in React Router

Next Article

Life2vec Crypto: The Ultimate Beginner's Guide
← Back to the blog
geekskai Logo
geekskai

Public tools for developers and creators, plus optional Geekskai Audio Toolkit plans. Built with care.

Popular Tools

SoundCloud DownloaderSoundCloud to MP3SoundCloud to WAVSoundCloud PlaylistSoundCloud Artwork
View All Tools

Resources

BlogAbout MePricingTagsProjectsPrivacy PolicyTerms of ServiceRefund Policy

Connect With Us

mailMail
githubGitHub
twitterTwitter
linkedinLinkedin
© 2026 geekskai • All rights reserved
React swag shop client example

A product card and a cart must update the same state. In this example, I keep that state in one parent-owned Hook, pass operations to the cards and cart, and derive the total from the committed cart lines. There is no separate empty cart state hidden inside Cart.

This is a client-side exercise, not a checkout or inventory service. The two sample products use USD integer cents. Quantities follow a demo policy of 1–99; that cap is not a stock guarantee. There are no orders, accounts, payments, or persistence across page reloads.

Set up the fixed React and Vite project

Use Node 22.13 or newer. Create these files in a new directory, run npm install, and retain the generated lockfile. React/React DOM are fixed at 19.3.0, with Vite 8.2.2 and plugin-react 6.0.4. Create React App is no longer the recommended starting point for a new project.

package.json

{
  "name": "react-workflow-example",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "19.3.0",
    "react-dom": "19.3.0"
  },
  "devDependencies": {
    "vite": "8.2.2",
    "@vitejs/plugin-react": "6.0.4"
  }
}

index.html

<!doctype html>
<html lang="en">
  <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>React workflow example</title></head>
  <body><div id="root"></div><script type="module" src="/src/main.jsx"></script></body>
</html>

vite.config.js

import { defineConfig } from "vite"
import react from "@vitejs/plugin-react"

export default defineConfig({ plugins: [react()] })

src/main.jsx

import { StrictMode } from "react"
import { createRoot } from "react-dom/client"
import App from "./App.jsx"

createRoot(document.getElementById("root")).render(<StrictMode><App /></StrictMode>)

Share one cart state and validate quantity text

The state stores one line per product ID. Repeated additions merge into that line, and functional updates preserve consecutive actions. Quantity input stays text until validation succeeds; an empty string must not silently become zero.

src/cart.js

import { useState } from "react"

export const MAX_CART_QUANTITY = 99
export const PRODUCTS = [
  { id: "tee", name: "React Tee", priceCents: 1900 },
  { id: "mug", name: "React Mug", priceCents: 1200 },
]
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })

export function formatPrice(cents) {
  return usd.format(cents / 100)
}

export function parseCartQuantity(text) {
  const trimmedText = text.trim()
  const quantity = Number(trimmedText)
  if (!/^\d+$/.test(trimmedText) || !Number.isSafeInteger(quantity) || quantity < 1 || quantity > MAX_CART_QUANTITY) {
    return { quantity: null, error: "Enter a whole quantity from 1 to 99." }
  }
  return { quantity, error: "" }
}

export function addCartProduct({ cartLines, product }) {
  const existing = cartLines.find(line => line.id === product.id)
  if (!existing) {
    return [...cartLines, { ...product, quantity: 1 }]
  }
  return cartLines.map(line => line.id === product.id
    ? { ...line, quantity: Math.min(line.quantity + 1, MAX_CART_QUANTITY) }
    : line)
}

export function cartTotalCents(cartLines) {
  return cartLines.reduce((total, line) => total + line.priceCents * line.quantity, 0)
}

export function useCart() {
  const [cartLines, setCartLines] = useState([])
  function addProduct(product) {
    setCartLines(previousLines => addCartProduct({ cartLines: previousLines, product }))
  }
  function updateQuantity({ productId, text }) {
    const result = parseCartQuantity(text)
    if (result.error) {
      return result.error
    }
    setCartLines(previousLines => previousLines.map(line => line.id === productId ? { ...line, quantity: result.quantity } : line))
    return ""
  }
  function removeProduct(productId) {
    setCartLines(previousLines => previousLines.filter(line => line.id !== productId))
  }
  return { cartLines, addProduct, updateQuantity, removeProduct }
}

The small, bounded example keeps subtotals and totals as safe integer cents. A real checkout must obtain authoritative products, prices, quantities, and totals from its server rather than trusting this browser state.

Render the cart and commit quantity edits

Each row keeps its product ID as its key. The quantity editor has a separate local draft and resets when the committed quantity changes, including a repeated Add action. Editing text alone does not change the subtotal. Apply quantity either commits a valid value or leaves the cart unchanged with an error.

src/Cart.jsx

import { useId, useState } from "react"
import { cartTotalCents, formatPrice } from "./cart.js"

function QuantityEditor({ line, onQuantityChange }) {
  const inputId = useId()
  const [draftQuantity, setDraftQuantity] = useState(String(line.quantity))
  const [errorMessage, setErrorMessage] = useState("")
  function handleSubmit(event) {
    event.preventDefault()
    const quantityError = onQuantityChange({ productId: line.id, text: draftQuantity })
    setErrorMessage(quantityError)
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor={inputId}>Quantity for {line.name}</label>
      <input id={inputId} name="quantity" inputMode="numeric" value={draftQuantity}
        onChange={event => setDraftQuantity(event.target.value)} aria-invalid={Boolean(errorMessage)} />
      <button type="submit">Apply quantity</button>
      {errorMessage && <p role="alert">{errorMessage}</p>}
    </form>
  )
}

export function Cart({ cartLines, onQuantityChange, onRemoveProduct }) {
  return (
    <section aria-label="Shopping cart">
      <h2>Cart</h2>
      {cartLines.length === 0 && <p>Your cart is empty.</p>}
      <ul>
        {cartLines.map(line => (
          <li key={line.id} data-product-id={line.id}>
            <h3>{line.name}</h3>
            <p>Subtotal: {formatPrice(line.priceCents * line.quantity)}</p>
            {/* Reset this editor on a committed quantity change; the row keeps its product ID. */}
            <QuantityEditor key={line.quantity} line={line} onQuantityChange={onQuantityChange} />
            <button onClick={() => onRemoveProduct(line.id)}>Remove {line.name}</button>
          </li>
        ))}
      </ul>
      <p aria-live="polite">Total: {formatPrice(cartTotalCents(cartLines))}</p>
    </section>
  )
}

Connect the product cards to the same owner

ProductCard receives an actual callback. The Add control becomes disabled at the demo quantity cap, and Remove changes only the matching product ID.

src/App.jsx

import { Cart } from "./Cart.jsx"
import { MAX_CART_QUANTITY, PRODUCTS, formatPrice, useCart } from "./cart.js"
import "./App.css"

function ProductCard({ product, canAdd, onAddProduct }) {
  return (
    <article className="product-card">
      <h3>{product.name}</h3>
      <p>{formatPrice(product.priceCents)}</p>
      <button disabled={!canAdd} onClick={() => onAddProduct(product)}>Add {product.name}</button>
    </article>
  )
}

export default function App() {
  const { cartLines, addProduct, updateQuantity, removeProduct } = useCart()
  return (
    <main>
      <h1>React swag cart demo</h1>
      <div className="product-grid">
        {PRODUCTS.map(product => {
          const quantity = cartLines.find(line => line.id === product.id)?.quantity || 0
          return <ProductCard key={product.id} product={product} canAdd={quantity < MAX_CART_QUANTITY} onAddProduct={addProduct} />
        })}
      </div>
      <Cart cartLines={cartLines} onQuantityChange={updateQuantity} onRemoveProduct={removeProduct} />
    </main>
  )
}

The original grid rules can be kept as a basic layout example. They are not a claim that every device and content length has been visually tested.

src/App.css

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 2rem;
  padding: 2rem;
}

@media (max-width: 768px) {
  .product-grid {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 1rem;
    padding: 1rem;
  }
}

Run npm run dev to open the client example, and npm run build to check its production bundle. The build does not create a store backend or a checkout service.

Check the cart loop

ActionExpected result
Open the appTwo products and an empty cart
Add React Tee twiceOne tee line with quantity 2 and a $38.00 subtotal
Add React Mug onceA separate mug line; total $50.00
Type a quantity without applyingThe committed subtotal stays unchanged
Apply 3 to the teeTee subtotal $57.00; the mug remains quantity 1
Apply empty, negative, fractional, non-numeric, or over-99 textVisible validation error; committed quantities and total stay unchanged
Remove one productOnly that ID disappears; the total is derived again
Reload the pageThe demo cart starts empty

Use labels and keyboard submission when checking the form. These state checks do not validate real pricing, payment security, stock, or a production checkout.

Questions about extending the example

Do I need Redux or Zustand? Not for this small shared parent state. Use another owner only when the application's actual state lifetime and consumers justify it.

Can this become a real shop? A production shop needs separate server-owned catalog, inventory, checkout, authentication when required, and order handling. Those are additional integrations; the client total above is a display calculation, not an amount to charge.

Where do product images and search fit? Add them only when the catalog and browsing task need them. Neither is necessary to demonstrate the cart state and quantity behavior here.

References

  • React sharing state between components
  • Updating arrays in state
  • Controlled inputs
  • React's Create React App retirement notice
  • Vite getting started