Menu

Components

Number Field

A field for typing a number, with buttons to step it up and down. Built on react-aria-components.

Introduction

Number Field is for values that are numbers: a quantity, a price, an age. The user can type the number or step it with the buttons, the arrow keys or the scroll wheel, and the value is always a real number in your code, never a string to parse.

  • minValue, maxValue and step. Out-of-range input is snapped back when the field loses focus.
  • Formatting for the user's language: currency, percent, units and decimals, through formatOptions.
  • Keyboard: Arrow Up and Down step, Page Up and Down step by ten, Home and End jump to the limits.
  • Works in a form: give it a name and the number is submitted with it.

For a code or an ID made of digits (a phone number, a PIN), use Text Field or Input OTP instead: they are text, not quantities.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx

# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx

# npm
npm install react-aria-components tailwind-variants tailwind-merge clsx

Manual installation

Copy these files into your project and keep the paths, or adjust the imports.

1. Add the styles

src/types/number-field-styles.tsShow code
import { tv } from "tailwind-variants";

// The frame holds the input and the stepper buttons. It clips them to its
// rounded corners, and the focus ring wraps all of it.
export const numberFieldStyles = tv({
  slots: {
    frame: [
      "flex w-full items-stretch overflow-hidden rounded-md text-fg transition-colors",
      "focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-bg",
      "group-data-invalid/number-field:border-danger",
      "group-data-disabled/number-field:opacity-50",
    ],
    input:
      "h-full min-w-0 flex-1 bg-transparent tabular-nums outline-none placeholder:text-muted-fg read-only:cursor-default",
    // A button that adds or subtracts one step.
    step: [
      "flex shrink-0 cursor-pointer items-center justify-center text-muted-fg outline-none transition-colors",
      "data-hovered:bg-muted data-hovered:text-fg data-pressed:bg-muted/70",
      "data-disabled:pointer-events-none data-disabled:opacity-40",
      "[&_svg]:pointer-events-none",
    ],
    // Holds the two buttons of the stacked layout, one above the other.
    stack: "flex shrink-0 flex-col border-l",
  },
  variants: {
    variant: {
      outline: { frame: "border bg-transparent" },
      secondary: { frame: "bg-secondary text-secondary-fg" },
      ghost: { frame: "bg-transparent hover:bg-muted focus-within:bg-muted" },
    },
    size: {
      sm: { frame: "h-8 text-sm", step: "[&_svg]:size-3.5" },
      md: { frame: "h-9 text-sm", step: "[&_svg]:size-4" },
      lg: { frame: "h-11 text-base", step: "[&_svg]:size-5" },
    },
    controls: {
      sides: { input: "px-2 text-center", step: "" },
      stacked: { input: "px-3", step: "flex-1" },
      none: { input: "px-3", step: "" },
    },
  },
  compoundVariants: [
    { controls: "sides", size: "sm", class: { step: "w-8" } },
    { controls: "sides", size: "md", class: { step: "w-9" } },
    { controls: "sides", size: "lg", class: { step: "w-11" } },
    { controls: "stacked", size: "sm", class: { stack: "w-6" } },
    { controls: "stacked", size: "md", class: { stack: "w-7" } },
    { controls: "stacked", size: "lg", class: { stack: "w-8" } },
  ],
  defaultVariants: { variant: "outline", size: "md", controls: "sides" },
});

2. Add the Number Field file

src/components/ui/number-field/number-field.tsxShow code
"use client";

import type { ReactNode } from "react";
import {
  Button as AriaButton,
  NumberField as AriaNumberField,
  type NumberFieldProps as AriaNumberFieldProps,
  FieldError,
  Group,
  Input,
  Label,
  Text,
  type ValidationResult,
} from "react-aria-components";
import {
  ChevronDownIcon,
  ChevronUpIcon,
  MinusIcon,
  PlusIcon,
} from "@/components/icons";
import { cn } from "@/lib/cn";
import { numberFieldStyles } from "@/types/number-field-styles";

export interface NumberFieldProps
  extends Omit<AriaNumberFieldProps, "children" | "className"> {
  label?: ReactNode;
  /** Help text under the field. */
  description?: ReactNode;
  /** Shown when the field is invalid. A function receives the validation result. */
  errorMessage?: string | ((validation: ValidationResult) => string);
  placeholder?: string;
  /** Look of the field. */
  variant?: "outline" | "secondary" | "ghost";
  /** Size of the field. */
  size?: "sm" | "md" | "lg";
  /**
   * The buttons that change the number by one step: a minus and a plus on the
   * `"sides"`, two chevrons `"stacked"` at the end, or `"none"`.
   */
  controls?: "sides" | "stacked" | "none";
  className?: string;
}

/**
 * A field for typing a number, with buttons to step it up and down. Built on
 * react-aria's NumberField, so the arrow keys, Page Up and Down, Home and End,
 * the scroll wheel, formatting for the user's locale, and form submission
 * (`name`) come from there.
 *
 * `value` is a number, or `NaN` while the field is empty. Set `minValue`,
 * `maxValue` and `step` for the limits, and `formatOptions` (the options of
 * `Intl.NumberFormat`) to show currency, percent, units or decimals.
 *
 * @example
 * <NumberField label="Quantity" defaultValue={1} minValue={1} maxValue={10} />
 */
export function NumberField({
  label,
  description,
  errorMessage,
  placeholder,
  variant,
  size = "md",
  controls = "sides",
  className,
  ...props
}: NumberFieldProps) {
  const styles = numberFieldStyles({ variant, size, controls });

  return (
    <AriaNumberField
      {...props}
      className={cn(
        "group/number-field flex w-full flex-col gap-1.5",
        className,
      )}
    >
      {label ? (
        <Label className="text-sm font-medium group-data-required/number-field:after:ml-0.5 group-data-required/number-field:after:text-danger group-data-required/number-field:after:content-['*']">
          {label}
        </Label>
      ) : null}
      <Group className={styles.frame()}>
        {controls === "sides" ? (
          <AriaButton
            slot="decrement"
            className={cn(styles.step(), "border-r")}
          >
            <MinusIcon />
          </AriaButton>
        ) : null}
        <Input placeholder={placeholder} className={styles.input()} />
        {controls === "sides" ? (
          <AriaButton
            slot="increment"
            className={cn(styles.step(), "border-l")}
          >
            <PlusIcon />
          </AriaButton>
        ) : null}
        {controls === "stacked" ? (
          <div className={styles.stack()}>
            <AriaButton
              slot="increment"
              className={cn(styles.step(), "border-b")}
            >
              <ChevronUpIcon />
            </AriaButton>
            <AriaButton slot="decrement" className={styles.step()}>
              <ChevronDownIcon />
            </AriaButton>
          </div>
        ) : null}
      </Group>
      {description ? (
        <Text slot="description" className="text-sm text-muted-fg">
          {description}
        </Text>
      ) : null}
      <FieldError className="text-sm text-danger">{errorMessage}</FieldError>
    </AriaNumberField>
  );
}

It imports MinusIcon, PlusIcon, ChevronUpIcon and ChevronDownIcon from @/components/icons. Add those icons, or swap them for your own.

3. Use it

import { NumberField } from "@/components/ui/number-field/number-field";

Anatomy

A number field is a framed input with step buttons.

<NumberField
  label="Quantity"
  description="Up to 10 per order."
  defaultValue={1}
  minValue={1}
  maxValue={10}
/>
PartRendered asNotes
LabellabelNames the field. Clicking it focuses the input.
InputinputWhere the number is typed. It shows the formatted value.
Step buttonsbuttonSubtract or add one step. They sit on the sides, stacked at the end, or are left out.
Description / errortext under the fieldHelp text, replaced by the error message when the field is invalid.

Without a label, give the field an aria-label so a screen reader can name it.

Examples

Live previews with code you can copy.

Usage

Label

Every field needs a name. Use label, or aria-label when the label is written elsewhere.

Description

Help text under the field.

Up to 10 per order.

Minimum and maximum

The buttons stop at the limits, and a typed number outside them is snapped back on blur.

Step

How much a button press or an arrow key adds. Decimals work too.

Formatting

formatOptions takes the options of Intl.NumberFormat. The field shows the formatted text and still gives you a plain number.

Controls

Where the step buttons go: on both sides, stacked at the end, or left out (the arrow keys still work).

Uncontrolled

Let the field keep its own number. Start with defaultValue, and give it a name to read the value from a form.

Controlled

Keep the number in your own state with value and onChange. The value is NaN while the field is empty.

value: 3

Scroll wheel

While the field is focused, the mouse wheel changes the number. Set isWheelDisabled to turn that off.

Read only

The number can be selected and copied, but not changed. It is still submitted with a form.

Sizes

Variants

Disabled

Validation

Set isInvalid with an errorMessage. The field gets a red border and the message replaces the description.

You must be 18 or older.You must be at least 18.

Component API

Number Field takes the props below, plus everything the react-aria NumberField accepts.

PropTypeDefault
labelReactNode-
descriptionReactNode-
errorMessagestring | (validation) => string-
placeholderstring-
valuenumber-
defaultValuenumber-
onChange(value: number) => void-
minValuenumber-
maxValuenumber-
stepnumber1
formatOptionsIntl.NumberFormatOptions-
controls"sides" | "stacked" | "none""sides"
isWheelDisabledbooleanfalse
namestring-
variant"outline" | "secondary" | "ghost""outline"
size"sm" | "md" | "lg""md"
autoFocusbooleanfalse
isDisabledbooleanfalse
isReadOnlybooleanfalse
isInvalidbooleanfalse
isRequiredbooleanfalse
aria-labelstring- (when there is no label)