Number Input with Stepper Buttons
Numeric field with a minus and a plus button that step by a set amount and speed up while held. Use for small bounded quantities such as seats, nights or cart lines.
How it differs. Explicit decrement and increment buttons on either side of a centred, typeable value, with accelerating press and hold repeat and buttons that disable at the bounds.
Install
pnpm dlx shadcn@latest add @hazine/number-input-stepper-buttonsAdds 1 file, 1 Hazine item (@hazine/use-controllable-state), and 2 packages (lucide-react, class-variance-authority).
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
The demo in the preview, 364 lines
"use client"
import * as React from "react"
import { CircleAlert } from "lucide-react"
import { Label } from "@/components/ui/label"
import { NumberInputStepperButtons } from "@/components/hazine/number-input-stepper-buttons"
const PLAN_PRICE = 90
const INCLUDED_SEATS = 5
const EXTRA_SEAT_PRICE = 14
const MAX_SEATS = 250
const money = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 0,
})
const cents = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
})
const count = new Intl.NumberFormat("en-US")
function plural(amount: number, one: string, many: string) {
return `${count.format(amount)} ${amount === 1 ? one : many}`
}
export default function NumberInputStepperButtonsDemo() {
const id = React.useId()
const hintId = React.useId()
const [seats, setSeats] = React.useState(12)
const extraSeats = Math.max(0, seats - INCLUDED_SEATS)
const extraCost = extraSeats * EXTRA_SEAT_PRICE
return (
<div className="grid w-full max-w-xs gap-4">
<div className="flex flex-col items-start gap-2">
<Label htmlFor={id}>Seats</Label>
<NumberInputStepperButtons
id={id}
aria-describedby={hintId}
value={seats}
onValueChange={setSeats}
min={1}
max={MAX_SEATS}
decrementLabel="Remove a seat"
incrementLabel="Add a seat"
formatValueText={(value) => plural(value, "seat", "seats")}
/>
<p id={hintId} className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">
The Team plan includes {INCLUDED_SEATS} seats.
</span>{" "}
Extra seats are {money.format(EXTRA_SEAT_PRICE)} each, up to{" "}
{MAX_SEATS} seats in total.
</p>
</div>
<div role="status">
<dl className="divide-y divide-border text-sm">
<div className="flex items-baseline justify-between gap-4 py-2">
<dt className="text-muted-foreground">Team plan</dt>
<dd className="tabular-nums">{money.format(PLAN_PRICE)}</dd>
</div>
<div className="flex items-baseline justify-between gap-4 py-2">
<dt className="text-muted-foreground">
{extraSeats === 0
? "No extra seats"
: plural(extraSeats, "extra seat", "extra seats")}
</dt>
<dd className="tabular-nums">{money.format(extraCost)}</dd>
</div>
<div className="flex items-baseline justify-between gap-4 py-2 font-semibold">
<dt>Total for {plural(seats, "seat", "seats")}</dt>
<dd className="flex items-baseline gap-1 tabular-nums">
{money.format(PLAN_PRICE + extraCost)}
<span className="text-xs font-normal text-muted-foreground">
/mo
</span>
</dd>
</div>
</dl>
</div>
</div>
)
}
function InvalidScenario() {
const id = React.useId()
const messageId = React.useId()
const [nights, setNights] = React.useState(0)
const invalid = nights < 1
return (
<div className="flex flex-col items-start gap-2">
<Label htmlFor={id}>Nights</Label>
<NumberInputStepperButtons
id={id}
value={nights}
onValueChange={setNights}
min={0}
max={14}
aria-invalid={invalid}
aria-describedby={messageId}
decrementLabel="Remove a night"
incrementLabel="Add a night"
formatValueText={(value) => plural(value, "night", "nights")}
/>
{invalid ? (
<p
id={messageId}
className="flex items-center gap-1.5 text-sm text-destructive"
>
<CircleAlert aria-hidden="true" className="size-3.5 shrink-0" />
Choose at least 1 night to see prices.
</p>
) : (
<p id={messageId} className="text-sm text-muted-foreground">
Stays run from 1 to 14 nights.
</p>
)}
</div>
)
}
function DisabledScenario() {
const id = React.useId()
const reasonId = React.useId()
return (
<div className="flex flex-col items-start gap-2">
<Label htmlFor={id}>Seats</Label>
<NumberInputStepperButtons
id={id}
aria-describedby={reasonId}
defaultValue={12}
min={1}
max={MAX_SEATS}
disabled
/>
<p id={reasonId} className="text-sm text-muted-foreground">
Seats are locked until the open invoice is paid.
</p>
</div>
)
}
function ReadOnlyScenario() {
const id = React.useId()
const reasonId = React.useId()
return (
<div className="flex flex-col items-start gap-2">
<Label htmlFor={id}>Seats</Label>
<NumberInputStepperButtons
id={id}
aria-describedby={reasonId}
defaultValue={INCLUDED_SEATS}
readOnly
/>
<p id={reasonId} className="text-sm text-muted-foreground">
Set by the Team plan. Only the workspace owner can change it.
</p>
</div>
)
}
function BoundsScenario() {
const id = React.useId()
const hintId = React.useId()
const [guests, setGuests] = React.useState(8)
return (
<div className="flex flex-col items-start gap-2">
<Label htmlFor={id}>Guests</Label>
<NumberInputStepperButtons
id={id}
aria-describedby={hintId}
value={guests}
onValueChange={setGuests}
min={1}
max={8}
decrementLabel="Remove a guest"
incrementLabel="Add a guest"
formatValueText={(value) => plural(value, "guest", "guests")}
/>
<p id={hintId} className="text-sm text-muted-foreground">
<span className="font-medium text-foreground tabular-nums">
{guests} of 8
</span>{" "}
beds taken. The Fjord cabin sleeps 8.
</p>
</div>
)
}
function DecimalScenario() {
const id = React.useId()
const hintId = React.useId()
const [weight, setWeight] = React.useState(2.5)
// Parcel rate: 4.20 up to 1 kg, then 0.90 for each further half kilogram
// or part of one, so a typed 2.3 kg is charged as 2.5 kg.
const postage = 4.2 + Math.max(0, Math.ceil((weight - 1) / 0.5)) * 0.9
return (
<div className="flex flex-col items-start gap-2">
<Label htmlFor={id}>Parcel weight</Label>
<div className="flex items-center gap-2">
<NumberInputStepperButtons
id={id}
aria-describedby={hintId}
value={weight}
onValueChange={setWeight}
min={0.5}
max={30}
step={0.5}
largeStep={5}
density="comfortable"
decrementLabel="Remove half a kilogram"
incrementLabel="Add half a kilogram"
formatValueText={(value) => plural(value, "kilogram", "kilograms")}
/>
<span className="text-xs text-muted-foreground">kg</span>
</div>
<p id={hintId} role="status" className="text-sm text-muted-foreground">
<span className="font-medium text-foreground tabular-nums">
{cents.format(postage)}
</span>{" "}
postage. Parcels go from 0.5 to 30 kg.
</p>
</div>
)
}
const PALLET_UNITS = 500
function OverflowScenario() {
const id = React.useId()
const hintId = React.useId()
const [units, setUnits] = React.useState(1250000)
return (
<div className="flex w-full max-w-xs flex-col items-start gap-2">
<Label htmlFor={id}>
Units to reorder for the Rotterdam cold storage warehouse, second
quarter
</Label>
<NumberInputStepperButtons
id={id}
aria-describedby={hintId}
value={units}
// The warehouse ships whole pallets, so a typed amount snaps to one.
onValueChange={(next) =>
setUnits(Math.round(next / PALLET_UNITS) * PALLET_UNITS)
}
min={0}
max={9999500}
step={PALLET_UNITS}
decrementLabel={`Remove one pallet of ${PALLET_UNITS} units`}
incrementLabel={`Add one pallet of ${PALLET_UNITS} units`}
formatValueText={(value) => plural(value, "unit", "units")}
/>
<p id={hintId} role="status" className="text-sm text-muted-foreground">
<span className="font-medium text-foreground tabular-nums">
{plural(units / PALLET_UNITS, "pallet", "pallets")}
</span>{" "}
of {PALLET_UNITS} units each.
</p>
</div>
)
}
interface Line {
id: string
name: string
unitPrice: number
quantity: number
stock: number
}
const LINES: Line[] = [
{ id: "beans", name: "Kiambu filter roast, 250 g", unitPrice: 18.5, quantity: 2, stock: 6 },
{ id: "papers", name: "Paper filters, pack of 100", unitPrice: 9, quantity: 1, stock: 20 },
{ id: "kettle", name: "Pour over kettle, 600 ml", unitPrice: 32, quantity: 3, stock: 3 },
]
function CartLine({
line,
onQuantityChange,
}: {
line: Line
onQuantityChange: (quantity: number) => void
}) {
const id = React.useId()
return (
<li className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 py-3">
<div className="min-w-0 flex-1">
<Label htmlFor={id} className="text-sm font-semibold">
<span className="sr-only">Quantity, </span>
{line.name}
</Label>
<p className="mt-0.5 text-xs text-muted-foreground tabular-nums">
{cents.format(line.unitPrice)} each, {line.stock} in stock
</p>
</div>
<div className="flex items-center gap-4">
<NumberInputStepperButtons
id={id}
value={line.quantity}
onValueChange={onQuantityChange}
min={1}
max={line.stock}
density="compact"
decrementLabel={`Decrease quantity, ${line.name}`}
incrementLabel={`Increase quantity, ${line.name}`}
/>
<p className="min-w-16 text-end text-sm font-semibold tabular-nums">
<span className="sr-only">Line total </span>
{cents.format(line.unitPrice * line.quantity)}
</p>
</div>
</li>
)
}
function CartLinesScenario() {
const [lines, setLines] = React.useState(LINES)
const items = lines.reduce((sum, line) => sum + line.quantity, 0)
const subtotal = lines.reduce(
(sum, line) => sum + line.unitPrice * line.quantity,
0
)
return (
<div className="w-full max-w-md">
<ul className="divide-y divide-border border-y border-border">
{lines.map((line) => (
<CartLine
key={line.id}
line={line}
onQuantityChange={(quantity) =>
setLines((current) =>
current.map((entry) =>
entry.id === line.id ? { ...entry, quantity } : entry
)
)
}
/>
))}
</ul>
<p
role="status"
className="flex items-baseline justify-between gap-4 py-3 text-sm font-semibold"
>
<span>Subtotal, {plural(items, "item", "items")}</span>
<span className="tabular-nums">{cents.format(subtotal)}</span>
</p>
</div>
)
}
export const scenarios = {
invalid: InvalidScenario,
disabled: DisabledScenario,
"read-only": ReadOnlyScenario,
bounds: BoundsScenario,
decimal: DecimalScenario,
overflow: OverflowScenario,
"cart-lines": CartLinesScenario,
}
Props11
- value
- number
- defaultValue
- number
- onValueChange
- (value: number) => void
- min
- number = Number.NEGATIVE_INFINITY
- max
- number = Number.POSITIVE_INFINITY
- step
- number = 1
- largeStep
- number = step * 10
- Amount for Page Up and Page Down. Defaults to ten steps.
- locale
- string = "en-US"
- BCP 47 tag. Sets the group and decimal separators the field shows and accepts. Digits are always Latin.
- decrementLabel
- string = "Decrease"
- incrementLabel
- string = "Increase"
- formatValueText
- (value: number) => string
- Spoken form of the value for assistive technology, for example "12 seats".
Also accepts every prop of Omit< React.ComponentProps<"input">, | "value" | "defaultValue" | "onChange" | "type" | "role" | "min" | "max" | "step" > and VariantProps<typeof numberInputStepperButtonsVariants>.
Accessibility
- Keyboard
Keyboard support for Number Input with Stepper Buttons Key Effect Digits and separators Edit the value as text. It is clamped to the bounds when committed Arrow Up, Arrow Down Increase or decrease by one step, starting from typed text when there is any Page Up, Page Down Increase or decrease by the large step Home, End Set the minimum or maximum, when one is defined. Otherwise the caret moves as usual Shift, Alt, Control or Command with any key above Left to the browser, so text selection and shortcuts keep working Enter Commit typed text, then submit the form as usual Escape Discard typed text Tab Commit typed text and leave the field. The step buttons are skipped - Screen reader
Text input with role spinbutton and value attributes, chosen over type number because the native control changes on scroll and cannot show grouped digits or carry value text. Step buttons are named and outside the tab order.
- Reduced motion
- No motion. Colour transitions only.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies3
- @hazine/use-controllable-state
- lucide-react
- class-variance-authority
Filled chips are registry items the CLI adds for you. Outlined chips are npm packages.
Tokens shipped0
None. The item is styled by the tokens your theme already has.