# NumberInput

A number input component that allows users to enter numeric values and increment or decrement them using stepper buttons. Built with React Aria's `useNumberField` for accessibility and the Cube `tasty` style system for theming.

## When to Use

- Collect numeric input (quantities, prices, ages, etc.)
- Allow users to increment/decrement values with stepper controls
- Enforce min/max/step constraints on numbers
- Build forms with validation and field decoration
- Support both controlled and uncontrolled usage

## Component

---

### Properties

- **`value`** `number | null` — The numeric value in controlled mode. `null` clears the field and keeps it controlled
- **`defaultValue`** `number` — The default numeric value in uncontrolled mode
- **`placeholder`** `string` — Placeholder text when input is empty
- **`icon`** `ReactElement` — Icon element rendered before the input
- **`prefix`** — Input decoration before the main input
- **`suffix`** — Input decoration after the main input
- **`tooltip`** `string | TooltipProviderProps` — The input's own tooltip, opened on hover over the field box and on keyboard focus. A disabled input with a tooltip stays focusable, so the keyboard reaches it too. See [TextInput](./TextInput.md#with-a-tooltip) for the behaviour. A disabled number input with a tooltip doesn't step from the keys, the wheel or the steppers
- **`suffixPosition`** `'before' | 'after'` (default: `before`) — Position of `suffix` relative to the stepper buttons. `before` keeps a unit next to the number (`40 px ⌃⌄`); `after` places the suffix after the steppers. The validation/loading icon always comes before both
- **`actions`** `ReactNode` — Controls placed last, after the steppers and `suffix` whatever `suffixPosition` is
- **`hideStepper`** `boolean` (default: `false`) — Whether to hide the stepper buttons
- **`isInteger`** `boolean` (default: `false`) — Accepts whole numbers only: a phone shows its digit keyboard, and a typed fraction stays as typed and marks the field invalid with the translated "Enter a whole number.", or with the message of your own `{ type: 'integer' }` rule. Use it instead of `formatOptions={{ maximumFractionDigits: 0 }}`; see [Whole Numbers](./NumberInput.md#whole-numbers)
- **`minValue`** `number` — Minimum allowed value
- **`maxValue`** `number` — Maximum allowed value
- **`step`** `number` — Amount to increment or decrement the value
- **`formatOptions`** `Intl.NumberFormatOptions` — Options for formatting the displayed number value
- **`size`** `'small' | 'medium' | 'large'` (default: `medium`) — Input size
- **`shape`** `'default' | 'plain'` (default: `default`) — Shape of the field box. `plain` is square with no border at rest, for a field set flush in a container that draws its edges, such as a toolbar or a panel header. Its border keeps its width and shows on focus and in a valid or invalid state, so nothing shifts
- **`autoComplete`** `string` (default: `off`) — HTML [`autocomplete`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete) token that tells the browser what to autofill (`cc-number`, `one-time-code`, …). A number field opts out of autofill by default.
- **`isWheelDisabled`** `boolean` — Whether scrolling the mouse wheel changes the value
- **`decrementAriaLabel`** `string` — Custom aria-label for the decrement button, in place of the translated "Decrease {label}"
- **`incrementAriaLabel`** `string` — Custom aria-label for the increment button, in place of the translated "Increase {label}"
- **`inputProps`** `Props` — Direct props passed to the native input element, merged over the props React Aria generates: a key you set wins, and event handlers are chained rather than replaced
- **`wrapperProps`** `Props` — Direct props passed to the input wrapper element, merged with the `group` props React Aria puts there: event handlers are chained
- **`validate`** `(value: number) => ValidationError | true | null | undefined` — Client-side validation. React Aria sets `aria-invalid` from the returned errors at once; the invalid style and the message follow after the user edits or leaves the field, so an empty field does not open in red. A typed number is checked once it commits, on blur or `Enter`. An explicit `errorMessage` replaces the returned message, and an explicit `isInvalid` (or a form's validation) takes over from `validate` entirely
- **`onChange`** `(value: number) => void` — Callback fired when a new value is committed, not on each keystroke: when the field loses focus or `Enter` is pressed after typing, and at once when a stepper button, the mouse wheel or one of the keys in [Keyboard Events](#keyboard-events) changes it. Committing an empty field passes `NaN`
- **`onBlur`** `function` — Callback fired when the input loses focus
- **`onFocus`** `function` — Callback fired when the input receives focus
- **`onKeyDown`** `(e: KeyboardEvent) => void` — Callback fired when a key is pressed in the input. See [Keyboard Events](#keyboard-events)
- **`onKeyUp`** `(e: KeyboardEvent) => void` — Callback fired when a key is released in the input

#### Keyboard Events

`onKeyDown` and `onKeyUp` are attached to the `<input>` by React Aria's `useNumberField`, which handles some keys itself and runs that handling **before** your `onKeyDown`:

- `ArrowUp` / `ArrowDown` and `PageUp` / `PageDown` step the value, unless a modifier key is held
- `Home` / `End` set the value to `minValue` / `maxValue`, when those are set
- `Enter` commits the typed number, firing `onChange` when the value changed

Because they run first, `e.preventDefault()` in `onKeyDown` cannot cancel them: it cancels what the browser would do with the key, such as submitting a surrounding form on `Enter`, and keeps an `Escape` or `Tab` at the input (below). That makes NumberInput the exception among the fields with built-in key handling (`ComboBox`, `SearchComboBox`, `TagInput` and `CommandTextArea` run your handler first and skip their own handling for a key you prevent), and it is what makes an `Enter` handler work here: by the time it runs, the typed number is committed and any `onChange` for it has fired.

```jsx
<NumberInput
  label="Limit"
  onChange={setLimit}
  onKeyDown={(e) => {
    // `onChange` has already been called with the committed number.
    if (e.key === 'Enter') onCommit();
  }}
/>
```

The handler receives React Aria's keyboard event rather than a plain React one. Keys other than `Enter` continue to ancestors as usual; `Enter` stops at the input unless you call `e.continuePropagation()`. As in every field, an `Escape` or `Tab` your handler prevents stays at the input, so a surrounding `Dialog` neither closes nor moves focus on it.

### Base Properties

Supports [Base properties](../../BaseProperties.md)

### Field Properties

Supports all [Field properties](../../FieldProperties.md)

### Styling Properties

#### styles

Styles the input element. Its style props place and size the field: see [Field properties](../../FieldProperties.md).

**Sub-elements:**

- `InputWrapper` – container around the input field
- `Prefix` – wrapper around prefix content
- `Suffix` – wrapper around suffix content
- `State` – container for validation and loading icons
- `InputIcon` – wrapper around the main icon
- `ValidationIcon` – wrapper around validation state icons

#### inputStyles

Customizes the input element itself.

### Style Properties

These properties allow direct style application without using the `styles` prop:

- **Position:** `gridArea`, `order`, `gridColumn`, `gridRow`, `placeSelf`, `alignSelf`, `justifySelf`, `zIndex`, `margin`, `blockMargin`, `inlineMargin`, `inset`, `blockInset`, `inlineInset`, `position`, `scrollMargin`, `blockScrollMargin`, `inlineScrollMargin`, `scrollPadding`, `blockScrollPadding`, `inlineScrollPadding`
- **Dimension:** `width`, `height`, `blockSize`, `inlineSize`, `flexBasis`, `flexGrow`, `flexShrink`, `flex`

### Modifiers

The `mods` prop accepts the following modifiers you can override:

- **`focused`** `boolean` — Forces focus ring appearance.
- **`disabled`** `boolean` — Forces disabled appearance.
- **`readonly`** `boolean` — Set while `isReadOnly`: a recessed fill and a softer border, except in high contrast, and no hover state.
- **`invalid`** `boolean` — Forces invalid state styling.
- **`valid`** `boolean` — Forces valid state styling.
- **`hovered`** `boolean` — Forces hover appearance.
- **`prefix`** `boolean` — Indicates presence of prefix content.
- **`suffix`** `boolean` — Indicates presence of suffix content.
- **`shape`** `'default' | 'plain'` — Set from `shape`: `plain` drops the radius, and the border colour at rest.

## Variants

### Types

- `number` – Standard number input (default)

### Sizes

- `small` – Compact height for dense interfaces
- `medium` – Standard height for most use cases
- `large` – Emphasized height for important inputs

## Examples

### Basic Usage

```jsx
<NumberInput label="Quantity" placeholder="Enter a number" />
```

### With Stepper Hidden

```jsx
<NumberInput label="Amount" hideStepper />
```

### With a Unit Suffix

A unit sits between the number and the steppers. Pass `suffixPosition="after"` to put the suffix after the steppers instead.

```jsx
<NumberInput label="Width" defaultValue={40} suffix={<Text>px</Text>} />
```

### With Min/Max

```jsx
<NumberInput label="Age" minValue={0} maxValue={120} />
```

### Whole Numbers

`isInteger` keeps a typed or pasted fraction visible and refuses it. `formatOptions={{ maximumFractionDigits: 0 }}` drops a typed decimal separator instead, so `1000.50` becomes `100050`. The separator follows the locale: in `de-DE`, `1.000` is one thousand, and `1000,5` is refused. Every typed fraction digit is kept, whatever `formatOptions.maximumFractionDigits` says, and a currency shows no cents.

A phone shows its digit keyboard; an iPhone only with a `minValue` of 0 or more, because its digit pad has no minus key. Leave `step` unset: the steppers already add 1, and a `step` snaps a typed value to it, so `step={1}` rounds a fraction instead of refusing it. An empty field is left to `isRequired`.

The field does not round a fraction, because a rounded value is a changed value nobody confirmed: a pasted `1000.50` would be saved as `1001`, and a screen reader user would not hear about it. The error shows what was typed, says what to fix, and stops a Form from submitting until it is fixed. Outside a Form, `onChange` still reports the fraction, so check `Number.isInteger(value)` before you save it.

A value outside `minValue` or `maxValue` is first moved to the nearest bound, so `28.5` with `maxValue={28}` becomes `28` with no error. `isInteger` checks the value, not what the field shows: with `formatOptions={{ style: 'percent' }}`, `50%` is `0.5` and is refused.

```jsx
<NumberInput label="Budget amount" name="amount" isInteger minValue={0} />
```

To say it in your own words, add a `{ type: 'integer', message }` rule: its message replaces "Enter a whole number." under the field and in the Form, and shows once. A rule without a text message, or a legacy function rule, keeps the kit's. In a legacy Form, an optional field can't replace the kit's message, because a `type` rule there also refuses an empty field.

```jsx
<NumberInput
  isInteger
  isRequired
  label="Budget amount"
  name="amount"
  minValue={0}
  rules={[{ type: 'integer', message: 'Enter a whole dollar amount, without cents.' }]}
/>
```

### With Validation

```jsx
<NumberInput
  label="Price"
  isInvalid
  errorMessage="Price must be positive"
/>
```

## Accessibility

### Keyboard Navigation

- `Tab` – Moves focus to the input field
- `Shift + Tab` – Moves focus away from the input
- Arrow keys – Increment/decrement value
- `PageUp`/`PageDown` – Increment/decrement value
- `Home`/`End` – Set to min/max value
- `Enter` – Commits the typed value
- Standard text editing shortcuts

### Screen Reader Support

- Announces a text field described as "Number field", with its label, description and validation messages
- The stepper buttons are named after the field ("Increase Quantity", "Decrease Quantity"), translated with the UI Kit locale. With a label that is not text, the name is "Increase" or "Decrease" and the label is read after it. They are not in the `Tab` order, and pressing one does not close a popover the field sits in
- State changes like "invalid" or "required" are announced
- The loading indicator is visual only: `isLoading` is not announced

### ARIA Properties

- `aria-label`, `aria-labelledby` – Accessible name for the input
- `aria-describedby` – Links to description and error messages
- `aria-invalid` – Managed automatically based on `isInvalid` and `validate`
- `aria-required` – Set when `isRequired` is true
- Additional ARIA attributes supported by React Aria's `useNumberField`

## Best Practices

1. **Do**: Provide clear labels and helpful placeholder text

   ```jsx
   <NumberInput label="Quantity" placeholder="0" />
   ```

2. **Don't**: Use placeholder text as the only label

   ```jsx
   {/* Avoid this */}
   <NumberInput placeholder="Enter a number" />
   ```

3. **Accessibility**: Always provide proper labels for screen readers
4. **Validation**: Use `isInvalid` / `isValid` and `errorMessage` for user feedback
5. **Performance**: Use `defaultValue` for uncontrolled inputs when possible

## Integration with Forms

This component supports all [Field properties](../../FieldProperties.md) when used within a Form.

When the browser submits the form itself, as a plain `<form>` or a Form with `action` does, `name` submits the number through a hidden input: `1234.5`, not the formatted `1,234.5` the input shows. An empty field submits an empty string, and a disabled NumberInput submits nothing. Only a Form without `action` stops an `isInteger` field from submitting a fraction: a plain `<form>`, or a Form with `action`, submits `10.5`, so check `Number.isInteger` before it submits.

A form built with `Form.useController` stores a field the user clears as `null`, so `required` reports it and other rules skip it, and the submitted values carry `null`. The input's own `onChange` and `validate` still receive `NaN`. The legacy form keeps `NaN`.

## Suggested Improvements

- Provide `maxValue`/`minValue` indicator with value range
- Support for input masks and formatting

## Related Components

- [TextInput](./TextInput.md) – Single-line or multiline text input
- [Slider](./Slider.md) – For selecting a value from a range
