Primitiveinput

Number Field

Stable

Campo para um número exato, com botões de diminuir e aumentar nas pontas. Composto sobre Base UI Number Field, que interpreta o que foi digitado na localidade, respeita min, max e step e formata por Intl.NumberFormat (moeda, porcentagem). A caixa usa a mesma altura, borda, anel de foco e estado inválido do Input, e o NumberFieldScrubArea compõe o Label como rótulo que também ajusta o valor ao ser arrastado. Use quando o valor é contado ou medido e a precisão importa; para texto livre use Input, e para escolher uma posição aproximada num intervalo use Slider.

Instalação

npx up-web-ds add number-field

Gera minus, plus para a biblioteca de ícones do projeto (components.json → iconLibrary).

Preview

Basic

Sizes

Scrub Area

Bounds

De 1 a 5.
Em passos de meia hora.

Currency

Percentage

Disabled

Definido pelo plano Equipe.

Invalid

A sala comporta 30 pessoas. Reduza para continuar.

With Input

Controlled

5 × R$ 49,90 = R$ 249,50 por mês

All states

Basic

Sizes

Scrub Area

Bounds

De 1 a 5.
Em passos de meia hora.

Currency

Percentage

Disabled

Definido pelo plano Equipe.

Invalid

A sala comporta 30 pessoas. Reduza para continuar.

With Input

Controlled

5 × R$ 49,90 = R$ 249,50 por mês

Usage

Imports de Number Field
import {
  NumberField,
  NumberFieldDecrement,
  NumberFieldGroup,
  NumberFieldIncrement,
  NumberFieldInput,
} from '@/components/ui/number-field'
import { Label } from '@/components/ui/label'
import { useId } from 'react'
Number Field
function SeatsField() {
  const id = useId()

  return (
    <div className="w-full max-w-48">
      <NumberField id={id} defaultValue={5} min={1}>
        <Label htmlFor={id}>Quantidade de licenças</Label>
        <NumberFieldGroup>
          <NumberFieldDecrement />
          <NumberFieldInput />
          <NumberFieldIncrement />
        </NumberFieldGroup>
      </NumberField>
    </div>
  )
}

Props

NumberField

Props de NumberField
PropTypeDefaultDescription
size"default" | "sm" | "lg"'default'Height of the field. `default` is the height of `Input`, so the two line up side by side in a form; `sm` and `lg` follow the Button's scale.
allowOutOfRangebooleanfalseWhen 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.
allowWheelScrubbooleanfalseWhether to allow the user to scrub the input value with the mouse wheel while focused and hovering over the input.
classNamestring | ((state: NumberFieldRootState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
defaultValuenumbersem valor padrãoThe uncontrolled value of the field when it's initially rendered. To render a controlled number field, use the `value` prop instead.
disabledbooleanfalseWhether the component should ignore user interaction.
formstringsem valor padrãoIdentifies the form that owns the hidden input. Useful when the number field is rendered outside the form.
formatIntl.NumberFormatOptionssem valor padrãoOptions to format the input value.
idstringsem valor padrãoThe id of the input element.
inputRefReact.Ref<HTMLInputElement>sem valor padrãoA ref to access the hidden input element.
largeStepnumber10The 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.
localeIntl.LocalesArgumentsem valor padrãoThe locale of the input element. Defaults to the user's runtime locale.
maxnumbersem valor padrãoThe maximum value of the input element.
minnumbersem valor padrãoThe minimum value of the input element.
namestringsem valor padrãoIdentifies the field when a form is submitted.
onValueChange((value: number | null, eventDetails: NumberFieldRoot.ChangeEventDetails) => void)sem valor padrãoCallback 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: NumberFieldRoot.CommitEventDetails) => void)sem valor padrãoCallback 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.
readOnlybooleanfalseWhether the user should be unable to change the field value.
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, NumberFieldRootState>sem valor padrãoAllows 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.
requiredbooleanfalseWhether the user must enter a value before submitting a form.
smallStepnumber0.1The 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.
snapOnStepbooleanfalseWhether the value should snap to the nearest step when incrementing or decrementing.
stepnumber | "any"1Amount 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`.
styleReact.CSSProperties | ((state: NumberFieldRootState) => React.CSSProperties | undefined)sem valor padrãoStyle applied to the element, or a function that returns a style object based on the component's state.
valuenumber | nullsem valor padrãoThe raw numeric value of the field.

Estende NumberFieldPrimitive.Root.Props. Aceita também os atributos padrão de um elemento React (273 não listados).

NumberFieldGroup

Props de NumberFieldGroup
PropTypeDefaultDescription
classNamestring | ((state: NumberFieldGroupState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, NumberFieldGroupState>sem valor padrãoAllows 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.
styleReact.CSSProperties | ((state: NumberFieldGroupState) => React.CSSProperties | undefined)sem valor padrãoStyle applied to the element, or a function that returns a style object based on the component's state.

Estende NumberFieldPrimitive.Group.Props. Aceita também os atributos padrão de um elemento React (275 não listados).

NumberFieldDecrement

Props de NumberFieldDecrement
PropTypeDefaultDescription
classNamestring | ((state: NumberFieldDecrementState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
nativeButtonbooleantrueWhether 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>`).
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, NumberFieldDecrementState>sem valor padrãoAllows 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.
styleReact.CSSProperties | ((state: NumberFieldDecrementState) => React.CSSProperties | undefined)sem valor padrãoStyle applied to the element, or a function that returns a style object based on the component's state.

Estende NumberFieldPrimitive.Decrement.Props. Aceita também os atributos padrão de um elemento React (285 não listados).

NumberFieldIncrement

Props de NumberFieldIncrement
PropTypeDefaultDescription
classNamestring | ((state: NumberFieldIncrementState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
nativeButtonbooleantrueWhether 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>`).
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, NumberFieldIncrementState>sem valor padrãoAllows 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.
styleReact.CSSProperties | ((state: NumberFieldIncrementState) => React.CSSProperties | undefined)sem valor padrãoStyle applied to the element, or a function that returns a style object based on the component's state.

Estende NumberFieldPrimitive.Increment.Props. Aceita também os atributos padrão de um elemento React (285 não listados).

NumberFieldInput

Props de NumberFieldInput
PropTypeDefaultDescription
aria-roledescriptionstring'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.
classNamestring | ((state: NumberFieldInputState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, NumberFieldInputState>sem valor padrãoAllows 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.
styleReact.CSSProperties | ((state: NumberFieldInputState) => React.CSSProperties | undefined)sem valor padrãoStyle applied to the element, or a function that returns a style object based on the component's state.

Estende NumberFieldPrimitive.Input.Props. Aceita também os atributos padrão de um elemento React (304 não listados).

NumberFieldScrubArea

Props de NumberFieldScrubArea
PropTypeDefaultDescription
label, obrigatóriastringsem valor padrãoThe field's name. Rendered as the Label of its input.
classNamestring | ((state: NumberFieldScrubAreaState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
direction"horizontal" | "vertical"'horizontal'Cursor movement direction in the scrub area.
pixelSensitivitynumber2Determines how many pixels the cursor must move before the value changes. A higher value will make scrubbing less sensitive.
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, NumberFieldScrubAreaState>sem valor padrãoAllows 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.
styleReact.CSSProperties | ((state: NumberFieldScrubAreaState) => React.CSSProperties | undefined)sem valor padrãoStyle applied to the element, or a function that returns a style object based on the component's state.
teleportDistancenumbersem valor padrãoIf specified, determines the distance that the cursor may move from the center of the scrub area before it will loop back around.

Estende NumberFieldPrimitive.ScrubArea.Props. Aceita também os atributos padrão de um elemento React (275 não listados).

prop obrigatória.

Composition

O rótulo e a caixa são irmãos dentro do NumberField; os botões ficam dentro da caixa, nas pontas do input.

Composição de NumberField

NumberField

  • NumberFieldScrubArea
  • NumberFieldGroup
    • NumberFieldDecrement
    • NumberFieldInput
    • NumberFieldIncrement

Metadata

Notas de acessibilidade

Teclado verificado por teste e em navegador: o campo custa um único Tab stop, no input; ArrowUp e ArrowDown andam um step, Shift anda o largeStep, Home e End vão a min e max quando declarados, e o valor digitado é interpretado e limitado ao intervalo no blur. Os botões de passo ficam fora da sequência de tabulação de propósito — as setas já fazem o trabalho a partir do input — e continuam alcançáveis por ponteiro, toque e leitor de tela de toque. Leitor de tela verificado por teste: o input é um textbox nomeado pelo label associado por htmlFor (também quando o rótulo é o NumberFieldScrubArea), os botões são nomeados Diminuir e Aumentar em vez do Increase e Decrease do Base UI, apontam para o input por aria-controls e ficam desabilitados no limite que cruzariam; aria-invalid com aria-describedby liga o motivo ao campo, e um campo desabilitado recusa entrada. Touch verificado em navegador com emulação de toque em viewport de 375px: o campo tem 36px de altura, os botões medem acima do mínimo de 24x24, ganham uma área de toque de 44px sob pointer coarse, e o toque diminui e aumenta o valor. Reduced motion verificado com prefers-reduced-motion: reduce — as transições de cor do hover e de anel do foco não são movimento e permanecem; não existe deslocamento para desligar. Varredura axe WCAG 2.2 AA limpa em light e dark.

Classificação

Layer
Primitive
Domínio
Domain-free (compartilhado)
Categoria
input
Status
Stable

Origem e distribuição

Fonte
coss registry / number-field
Licença
MIT
Distribuição
Interna

Acessibilidade

  • Teclado: revisado
  • Leitor de tela: revisado
  • Touch: revisado
  • Reduced motion: revisado

Dependências

Pacotes
@base-ui/react
Ícones
minus, plus
Construído sobre
Label
Usado por
Nenhum ainda