# Number Input

A number input with stepper buttons, formatting and a draggable label.

Source: [number-input.tsx](https://github.com/jakejarvis/jarvis-ui/blob/main/src/components/ui/number-input.tsx)

```tsx
import { Field, FieldLabel } from "@/components/ui/field";
import { NumberInput } from "@/components/ui/number-input";

export default function NumberInputBasic() {
  return (
    <Field className="w-28">
      <FieldLabel>Seats</FieldLabel>
      <NumberInput defaultValue={3} min={1} max={10} />
    </Field>
  );
}
```

## Installation

Add the registry, once per project:

```bash
npx shadcn@latest registry add @jarvis=https://ui.jarv.is/r/{name}.json
```

Then add the component:

```bash
npx shadcn@latest add @jarvis/number-input
```

## Usage

```tsx
import { Field, FieldLabel } from "@/components/ui/field";
import { NumberInput } from "@/components/ui/number-input";

export function GuestsField() {
  return (
    <Field>
      <FieldLabel>Guests</FieldLabel>
      <NumberInput defaultValue={2} min={1} max={12} />
    </Field>
  );
}
```

A `FieldLabel` in the same [Field](https://ui.jarv.is/components/field.md) labels the input. Without a visible label,
give `NumberInput` an `aria-label`.

Without children, `NumberInput` renders its input and stepper buttons. To customize them, such as
to put a currency symbol before the number or a `NumberInputScrubArea` around the label, compose
the parts yourself:

```tsx
import {
  NumberInput,
  NumberInputDecrement,
  NumberInputGroup,
  NumberInputIncrement,
  NumberInputInput,
} from "@/components/ui/number-input";

export function PriceInput() {
  return (
    <NumberInput aria-label="Price" defaultValue={20}>
      <NumberInputGroup>
        <span>$</span>
        <NumberInputInput />
        <NumberInputDecrement />
        <NumberInputIncrement />
      </NumberInputGroup>
    </NumberInput>
  );
}
```

Either way, `NumberInput` passes its `aria-label` and `placeholder` to its `NumberInputInput`.

## Composition

- `NumberInput`
  - `NumberInputScrubArea`
  - `NumberInputGroup`
    - `NumberInputInput`
    - `NumberInputDecrement`
    - `NumberInputIncrement`

## Examples

### Formatting

`format` takes [`Intl.NumberFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options)
options, for decimals, percentages or units.

```tsx
import {
  NumberInput,
  NumberInputGroup,
  NumberInputInput,
  NumberInputDecrement,
  NumberInputIncrement,
} from "@/components/ui/number-input";

export default function NumberInputFormatting() {
  return (
    <div className="flex flex-wrap items-center gap-3">
      <NumberInput
        defaultValue={50}
        min={5}
        step={5}
        format={{ minimumFractionDigits: 2, maximumFractionDigits: 2 }}
        className="w-36"
      >
        <NumberInputGroup>
          <span>$</span>
          <NumberInputInput aria-label="Amount in USD" />
          <NumberInputDecrement />
          <NumberInputIncrement />
        </NumberInputGroup>
      </NumberInput>
      <NumberInput
        defaultValue={0.15}
        min={0}
        max={1}
        step={0.05}
        format={{ style: "percent" }}
        className="w-28"
        aria-label="Discount"
      />
    </div>
  );
}
```

### Scrub area

Wrap the label in a `NumberInputScrubArea` to change the value by dragging it sideways.

```tsx
import { Field, FieldLabel } from "@/components/ui/field";
import {
  NumberInput,
  NumberInputGroup,
  NumberInputInput,
  NumberInputDecrement,
  NumberInputIncrement,
  NumberInputScrubArea,
} from "@/components/ui/number-input";

export default function NumberInputScrub() {
  return (
    <div className="flex flex-wrap items-center gap-3">
      <Field className="w-32">
        <NumberInput defaultValue={240} min={0} max={1200}>
          <NumberInputScrubArea>
            <FieldLabel>Width</FieldLabel>
          </NumberInputScrubArea>
          <NumberInputGroup className="pr-2">
            <NumberInputInput />
            <span>px</span>
          </NumberInputGroup>
        </NumberInput>
      </Field>
      <Field className="w-32">
        <NumberInput defaultValue={0.8} min={0} max={1} step={0.01} format={{ style: "percent" }}>
          <NumberInputScrubArea>
            <FieldLabel>Opacity</FieldLabel>
          </NumberInputScrubArea>
          <NumberInputGroup>
            <NumberInputInput />
            <NumberInputDecrement />
            <NumberInputIncrement />
          </NumberInputGroup>
        </NumberInput>
      </Field>
    </div>
  );
}
```

### Large

Set `size="lg"` on `NumberInput` for a taller input, or `size="sm"` for a shorter one.

```tsx
"use client";

import * as React from "react";

import { Button } from "@/components/ui/button";
import {
  NumberInput,
  NumberInputGroup,
  NumberInputInput,
  NumberInputDecrement,
  NumberInputIncrement,
} from "@/components/ui/number-input";
import { Select, SelectContent, SelectItem, SelectTrigger } from "@/components/ui/select";
import { toast } from "@/components/ui/toast";

const cards = { visa: "Visa •• 7391", amex: "Amex •• 1008" };

export default function NumberInputLarge() {
  const [amount, setAmount] = React.useState<number | null>(50);

  return (
    <div className="flex flex-wrap items-center gap-3">
      <NumberInput
        value={amount}
        onValueChange={setAmount}
        min={5}
        max={500}
        step={5}
        format={{ minimumFractionDigits: 2, maximumFractionDigits: 2 }}
        size="lg"
        className="w-40"
      >
        <NumberInputGroup>
          <span>$</span>
          <NumberInputInput aria-label="Amount in USD" />
          <NumberInputDecrement />
          <NumberInputIncrement />
        </NumberInputGroup>
      </NumberInput>
      <Select items={cards} defaultValue="visa">
        <SelectTrigger size="lg" aria-label="Payment method" />
        <SelectContent>
          {Object.entries(cards).map(([value, label]) => (
            <SelectItem key={value} value={value}>
              {label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
      <Button
        variant="secondary"
        size="lg"
        disabled={amount === null}
        onClick={() => toast.add({ title: "Funds added", type: "success" })}
      >
        Add ${amount === null ? "" : amount.toFixed(2)}
      </Button>
    </div>
  );
}
```

### Steppers on either side

Put `NumberInputDecrement` before `NumberInputInput` to place the buttons on either side of the
value. To center the value with a label after it, size the input to its value with
`field-sizing-content`, and push the buttons to the edges with `mr-auto` and `ml-auto`. In browsers
without `field-sizing`, the input's `size` attribute sets its width in characters.

```tsx
import {
  NumberInput,
  NumberInputDecrement,
  NumberInputGroup,
  NumberInputIncrement,
  NumberInputInput,
} from "@/components/ui/number-input";

export default function NumberInputSteppersEitherSide() {
  return (
    <NumberInput aria-label="Seats" defaultValue={8} min={2} max={12} size="lg" className="w-48">
      <NumberInputGroup>
        <NumberInputDecrement className="mr-auto" />
        <NumberInputInput
          size={2}
          className="field-sizing-content w-auto flex-none self-baseline text-right"
        />
        <span className="self-baseline">seats</span>
        <NumberInputIncrement className="ml-auto" />
      </NumberInputGroup>
    </NumberInput>
  );
}
```

### Display

Set `variant="display"` to show the value in large type between round stepper buttons, for a
[Sheet](https://ui.jarv.is/components/sheet.md) or [Card](https://ui.jarv.is/components/card.md) built around a single number. To label the
number, compose the parts and add a caption under `NumberInputInput`.

```tsx
import {
  NumberInput,
  NumberInputDecrement,
  NumberInputGroup,
  NumberInputIncrement,
  NumberInputInput,
} from "@/components/ui/number-input";

export default function NumberInputDisplay() {
  return (
    <NumberInput
      variant="display"
      aria-label="Cups of water per day"
      defaultValue={8}
      min={1}
      max={16}
    >
      <NumberInputGroup>
        <NumberInputDecrement />
        <div className="flex flex-col items-center">
          <NumberInputInput />
          <span className="text-2xs text-faint">cups per day</span>
        </div>
        <NumberInputIncrement />
      </NumberInputGroup>
    </NumberInput>
  );
}
```

### Disabled

```tsx
import { NumberInput } from "@/components/ui/number-input";

export default function NumberInputDisabled() {
  return <NumberInput defaultValue={12} disabled className="w-28" aria-label="Quantity" />;
}
```

### Read-only

```tsx
import { NumberInput } from "@/components/ui/number-input";

export default function NumberInputReadOnly() {
  return <NumberInput defaultValue={12} readOnly className="w-28" aria-label="Quantity" />;
}
```

### Invalid

Set `invalid` on the [`Field`](https://ui.jarv.is/components/field.md) and explain the problem with a `FieldError`.

```tsx
import { Field, FieldError, FieldLabel } from "@/components/ui/field";
import { NumberInput } from "@/components/ui/number-input";

export default function NumberInputInvalid() {
  return (
    <Field invalid className="w-40">
      <FieldLabel>Quantity</FieldLabel>
      <NumberInput defaultValue={0} min={0} />
      <FieldError>Order at least one.</FieldError>
    </Field>
  );
}
```

## Props

| Part | Extends |
| --- | --- |
| `NumberInput` | [`NumberField.Root`](https://base-ui.com/react/components/number-field#root) |
| `NumberInputGroup` | [`NumberField.Group`](https://base-ui.com/react/components/number-field#group) |
| `NumberInputInput` | [`NumberField.Input`](https://base-ui.com/react/components/number-field#input) |
| `NumberInputDecrement` | [`NumberField.Decrement`](https://base-ui.com/react/components/number-field#decrement) |
| `NumberInputIncrement` | [`NumberField.Increment`](https://base-ui.com/react/components/number-field#increment) |
| `NumberInputScrubArea` | [`NumberField.ScrubArea`](https://base-ui.com/react/components/number-field#scrubarea) |

Base UI's [styling](https://base-ui.com/react/handbook/styling) and [composition](https://base-ui.com/react/handbook/composition) guides say more about `className`, `style` and `render`.

### NumberInput

| Prop                | Type                                                                                         | Default     | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| ------------------- | -------------------------------------------------------------------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id?`               | `string`                                                                                     | —           | The id of the input element.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `min?`              | `number`                                                                                     | —           | The minimum value of the input element.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `max?`              | `number`                                                                                     | —           | The maximum value of the input element.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `allowOutOfRange?`  | `boolean`                                                                                    | `false`     | When true, direct text entry may be outside the `min`/`max` range without clamping, so native range underflow/overflow validation can occur. Step-based interactions (keyboard arrows, buttons, wheel, scrub) still clamp.                                                                                                                                                                                                                                                                                                                                                                                                              |
| `smallStep?`        | `number`                                                                                     | `0.1`       | The small step value of the input element when incrementing while the alt key is held. Snaps to multiples of this value when `snapOnStep` is enabled.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `step?`             | `number \| "any"`                                                                            | `1`         | Amount to increment and decrement with the buttons and arrow keys, or to scrub with pointer movement in the scrub area. To always enable step validation on form submission, specify the `min` prop explicitly in conjunction with this prop. Specify `step="any"` to always disable step validation; interactive stepping then uses a base amount of `1`, while the alt and shift keys still step by `smallStep` and `largeStep`.                                                                                                                                                                                                      |
| `largeStep?`        | `number`                                                                                     | `10`        | The large step value of the input element when incrementing while the shift key is held. Snaps to multiples of this value when `snapOnStep` is enabled.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `required?`         | `boolean`                                                                                    | `false`     | Whether the user must enter a value before submitting a form.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `disabled?`         | `boolean`                                                                                    | `false`     | Whether the component should ignore user interaction.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `readOnly?`         | `boolean`                                                                                    | `false`     | Whether the user should be unable to change the field value.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `name?`             | `string`                                                                                     | —           | Identifies the field when a form is submitted.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `form?`             | `string`                                                                                     | —           | Identifies the form that owns the hidden input. Useful when the number field is rendered outside the form.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `value?`            | `number \| null`                                                                             | —           | The raw numeric value of the field.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `defaultValue?`     | `number`                                                                                     | —           | The uncontrolled value of the field when it's initially rendered. To render a controlled number field, use the `value` prop instead.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `allowWheelScrub?`  | `boolean`                                                                                    | `false`     | Whether to allow the user to scrub the input value with the mouse wheel while focused and hovering over the input.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `snapOnStep?`       | `boolean`                                                                                    | `false`     | Whether the value should snap to the nearest step when incrementing or decrementing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `format?`           | `Intl.NumberFormatOptions`                                                                   | —           | Options to format the input value.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `onValueChange?`    | `((value: number \| null, eventDetails: NumberField.Root.ChangeEventDetails) => void)`       | —           | Callback fired when the number value changes. The `eventDetails.reason` indicates what triggered the change: - `'input-change'` for parseable typing or programmatic text updates - `'input-clear'` when the field becomes empty - `'input-blur'` when formatting (and clamping, if enabled) occurs on blur - `'input-paste'` for paste interactions - `'keyboard'` for arrow-key/Home/End stepping (typing digits uses `'input-change'`/`'input-clear'`) - `'increment-press'` / `'decrement-press'` for button presses on the increment and decrement controls - `'wheel'` for wheel-based scrubbing - `'scrub'` for scrub area drags |
| `onValueCommitted?` | `((value: number \| null, eventDetails: NumberField.Root.CommitEventDetails) => void)`       | —           | Callback function that is fired when the value is committed. It runs later than `onValueChange`, when: - The input is blurred after typing a value. - The pointer is released after scrubbing or pressing the increment/decrement buttons. It runs simultaneously with `onValueChange` when interacting with the keyboard or the mouse wheel. **Warning**: This is a generic event not a change event.                                                                                                                                                                                                                                  |
| `locale?`           | `Intl.LocalesArgument`                                                                       | `"en-US"`   | The locale of the input element. Defaults to the user's runtime locale.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `inputRef?`         | `React.Ref<HTMLInputElement>`                                                                | —           | A ref to access the hidden input element.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `aria-label?`       | `string`                                                                                     | —           | Defines a string value that labels the current element. Labels the input when there's no `FieldLabel`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `aria-labelledby?`  | `string`                                                                                     | —           | Identifies the element (or elements) that labels the current element. The `id` of the element that labels the input when there's no `FieldLabel`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `variant?`          | `"default" \| "display"`                                                                     | `"default"` | `display` shows the value large and centered between round stepper buttons.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `size?`             | `"default" \| "lg" \| "sm"`                                                                  | `"default"` | The height: `sm` 24px, `default` 28px, `lg` 32px. Only the `default` variant has sizes.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `placeholder?`      | `string`                                                                                     | —           | The input's placeholder.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `className?`        | `string \| ((state: NumberFieldRootState) => string \| undefined)`                           | —           | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `style?`            | `React.CSSProperties \| ((state: NumberFieldRootState) => React.CSSProperties \| undefined)` | —           | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `render?`           | `ComponentRenderFn<HTMLProps, NumberFieldRootState> \| React.ReactElement`                   | —           | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render.                                                                                                                                                                                                                                                                                                                                                                                                                                               |

### NumberInputGroup

| Prop         | Type                                                                                          | Default | Description                                                                                                                                                                               |
| ------------ | --------------------------------------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `className?` | `string \| ((state: NumberFieldGroupState) => string \| undefined)`                           | —       | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`     | `React.CSSProperties \| ((state: NumberFieldGroupState) => React.CSSProperties \| undefined)` | —       | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`    | `ComponentRenderFn<HTMLProps, NumberFieldGroupState> \| React.ReactElement`                   | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### NumberInputInput

| Prop                    | Type                                                                                                                                                     | Default          | Description                                                                                                                                                                               |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `aria-roledescription?` | `string`                                                                                                                                                 | `'Number field'` | A user-friendly description of the input's role for assistive tech. This is a role description, not an accessible name — use `Field.Label` or `aria-label` to name the control.           |
| `className?`            | `string \| ((state: NumberFieldInputState) => string \| undefined)`                                                                                      | —                | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`                | `React.CSSProperties \| ((state: NumberFieldInputState) => React.CSSProperties \| undefined)`                                                            | —                | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`               | `ComponentRenderFn<React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, NumberFieldInputState> \| React.ReactElement` | —                | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### NumberInputDecrement

| Prop            | Type                                                                                              | Default | Description                                                                                                                                                                               |
| --------------- | ------------------------------------------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `nativeButton?` | `boolean`                                                                                         | `true`  | Whether the component renders a native `<button>` element when replacing it via the `render` prop. Set to `false` if the rendered element is not a button (for example, `<div>`).         |
| `className?`    | `string \| ((state: NumberFieldDecrementState) => string \| undefined)`                           | —       | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`        | `React.CSSProperties \| ((state: NumberFieldDecrementState) => React.CSSProperties \| undefined)` | —       | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`       | `ComponentRenderFn<HTMLProps, NumberFieldDecrementState> \| React.ReactElement`                   | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### NumberInputIncrement

| Prop            | Type                                                                                              | Default | Description                                                                                                                                                                               |
| --------------- | ------------------------------------------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `nativeButton?` | `boolean`                                                                                         | `true`  | Whether the component renders a native `<button>` element when replacing it via the `render` prop. Set to `false` if the rendered element is not a button (for example, `<div>`).         |
| `className?`    | `string \| ((state: NumberFieldIncrementState) => string \| undefined)`                           | —       | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`        | `React.CSSProperties \| ((state: NumberFieldIncrementState) => React.CSSProperties \| undefined)` | —       | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`       | `ComponentRenderFn<HTMLProps, NumberFieldIncrementState> \| React.ReactElement`                   | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### NumberInputScrubArea

| Prop                | Type                                                                                              | Default        | Description                                                                                                                                                                               |
| ------------------- | ------------------------------------------------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `direction?`        | `"horizontal" \| "vertical"`                                                                      | `"horizontal"` | Cursor movement direction in the scrub area.                                                                                                                                              |
| `pixelSensitivity?` | `number`                                                                                          | `2`            | Determines how many pixels the cursor must move before the value changes. A higher value will make scrubbing less sensitive.                                                              |
| `teleportDistance?` | `number`                                                                                          | —              | If specified, determines the distance that the cursor may move from the center of the scrub area before it will loop back around.                                                         |
| `className?`        | `string \| ((state: NumberFieldScrubAreaState) => string \| undefined)`                           | —              | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`            | `React.CSSProperties \| ((state: NumberFieldScrubAreaState) => React.CSSProperties \| undefined)` | —              | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`           | `ComponentRenderFn<HTMLProps, NumberFieldScrubAreaState> \| React.ReactElement`                   | —              | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |
