Open this example in the interactive library
Live preview
Source code
// components/CartSubtotalCalculator.tsx
import { useState } from "react";
export default function CartSubtotalCalculator({
price = 24,
stock = 8,
}: { price?: number; stock?: number } = {}) {
const [qty, set] = useState(0);
return (
<label>
Quantity
<input
type="number"
min={0}
max={stock}
value={qty}
onChange={(e) => set(Math.min(stock, Math.max(0, Number(e.target.value))))}
/>
<output>Subtotal: ${(qty * price).toFixed(2)}</output>
</label>
);
}
