ForgeWP

Solution for the Variation Selector

A typed selection exercise with explicit availability feedback and no implied order creation or payment.

Solution for the variation selector

src/components/VariationExercise.tsx
1import { defineProduct, useWpProductVariations, useWpCurrency } from "@forgewp/woocommerce"
2
3const product = defineProduct({
4  id: 201, name: "Cotton shirt", type: "variable", price: "30.00",
5  attributes: [{ name: "size", options: ["Small", "Large"], variation: true }],
6  variations: [
7    { id: 202, attributes: { size: "Small" }, price: "30.00", stock_status: "instock" },
8    { id: 203, attributes: { size: "Large" }, price: "34.00", stock_status: "outofstock" },
9  ],
10})
11
12export default function VariationExercise() {
13  const selection = useWpProductVariations(product)
14  const { formatPrice } = useWpCurrency()
15  const ready = selection.isSelectionComplete && Boolean(selection.matchingVariation) && !selection.isOutOfStock
16  return <section aria-label="Variation exercise">
17    <label htmlFor="shirt-size">Size</label>
18    <select id="shirt-size" value={selection.selectedAttributes.size || ""}
19      onChange={event => selection.setAttribute("size", event.target.value)}>
20      <option value="">Choose a size</option>
21      <option value="Small">Small</option><option value="Large">Large</option>
22    </select>
23    <p>{formatPrice(selection.currentPrice, { decimals: 2 })}</p>
24    <p role="status">{!selection.isSelectionComplete ? "Choose a size." : ready ? "Available choice." : "Unavailable choice."}</p>
25    <button type="button" disabled={!ready}>Selection ready (demo)</button>
26    <button type="button" onClick={selection.resetAttributes}>Reset selection</button>
27  </section>
28}

This check does not reserve stock. The action demonstrates readiness only; production must validate stock and the selected variation on the server. Explicit decimals stabilize this fixture's display because the formatter otherwise can default to zero decimal places.