Skip to content

ComponentsForms & data

SourceSource

Number Input

A number field with decrement and increment buttons that respect min, max and step.

Use it when the number itself is what the reader is setting: a slowmode in seconds, a member limit, a retry count. The steppers are real buttons large enough for a finger, and the field between them still takes typing.

What is typed is kept as text until it reads as a number, so the field can be cleared on the way to a new value. A value outside the range is pulled back in when the field is left.

Root class newt-number
"use client"

import * as React from "react"

import { Field, FieldHelp, Label } from "@/registry/bases/newt/ui/form-fields"
import { NumberInput } from "@/registry/bases/newt/ui/number-input"

export default function NumberInputDemo() {
  const [seconds, setSeconds] = React.useState(15)

  return (
    <Field className="items-start">
      <Label htmlFor="newt-number-input-example">Slowmode</Label>
      <NumberInput
        id="newt-number-input-example"
        min={0}
        max={120}
        step={5}
        value={seconds}
        onValueChange={setSeconds}
      />
      <FieldHelp>
        {seconds === 0
          ? "Members can post freely."
          : `One message every ${seconds} seconds.`}
      </FieldHelp>
    </Field>
  )
}
<script setup lang="ts">
import { ref } from "vue"
import { Field, FieldHelp, Label } from "~~/registry/bases/newt/ui/form-fields"
import { NumberInput } from "~~/registry/bases/newt/ui/number-input"

const seconds = ref(15)
</script>

<template>
  <Field class="items-start">
    <Label for="newt-number-input-example">Slowmode</Label>
    <NumberInput
      id="newt-number-input-example"
      v-model="seconds"
      :min="0"
      :max="120"
      :step="5"
    />
    <FieldHelp>
      {{
        seconds === 0
          ? "Members can post freely."
          : `One message every ${seconds} seconds.`
      }}
    </FieldHelp>
  </Field>
</template>

Installation

npx newtui@latest add number-inputnpx shadcn@latest add @newtui/number-inputnpx shadcn-vue@latest add @newtui/number-inputpnpm dlx newtui@latest add number-inputpnpm dlx shadcn@latest add @newtui/number-inputpnpm dlx shadcn-vue@latest add @newtui/number-inputyarn dlx newtui@latest add number-inputyarn dlx shadcn@latest add @newtui/number-inputyarn dlx shadcn-vue@latest add @newtui/number-inputbunx newtui@latest add number-inputbunx shadcn@latest add @newtui/number-inputbunx shadcn-vue@latest add @newtui/number-inputdeno run -A npm:newtui@latest add number-inputdeno run -A npm:shadcn@latest add @newtui/number-inputdeno run -A npm:shadcn-vue@latest add @newtui/number-inputvlx newtui@latest add number-inputvlx shadcn@latest add @newtui/number-inputvlx shadcn-vue@latest add @newtui/number-inputvp dlx newtui@latest add number-inputvp dlx shadcn@latest add @newtui/number-inputvp dlx shadcn-vue@latest add @newtui/number-inputnubx newtui@latest add number-inputnubx shadcn@latest add @newtui/number-inputnubx shadcn-vue@latest add @newtui/number-inputnlx newtui@latest add number-inputnlx shadcn@latest add @newtui/number-inputnlx shadcn-vue@latest add @newtui/number-inputupx newtui@latest add number-inputupx shadcn@latest add @newtui/number-inputupx shadcn-vue@latest add @newtui/number-input

The shadcn CLI needs the @newtui registry in your components.json. Set it up.

Copy the source into your project

"use client"

import * as React from "react"

import { cn } from "@/lib/utils"

export interface NumberInputProps extends Omit<
  React.InputHTMLAttributes<HTMLInputElement>,
  "type" | "value" | "defaultValue" | "onChange" | "min" | "max" | "step"
> {
  /** Controlled value. Leave undefined to let the component own it. */
  value?: number
  defaultValue?: number
  onValueChange?: (value: number) => void
  min?: number
  max?: number
  step?: number
  invalid?: boolean
  /** Accessible names of the two stepper buttons. */
  decrementLabel?: string
  incrementLabel?: string
}

/** As many decimals as the step has, so 0.1 + 0.2 reads 0.3. */
function decimalsOf(step: number): number {
  const text = String(step)
  const point = text.indexOf(".")
  return point === -1 ? 0 : text.length - point - 1
}

const stepClassName =
  "inline-flex w-9 shrink-0 items-center justify-center text-newt-text-secondary transition-colors duration-fast ease-newt hover:bg-newt-bg-hover hover:text-newt-text-primary focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-newt-text-link disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-newt-text-secondary"

/*
 * A number field with its two steppers drawn as real buttons. The input stays
 * `type="number"`, so the arrow keys and the announced range are the
 * browser's. What is typed is kept as text until it parses, so a reader can
 * clear the field or type a minus sign on the way to a number; the value is
 * clamped to `min` and `max` when the field is left.
 */
const NumberInput = React.forwardRef<HTMLInputElement, NumberInputProps>(
  (
    {
      className,
      value,
      defaultValue,
      onValueChange,
      min,
      max,
      step = 1,
      invalid = false,
      disabled = false,
      decrementLabel = "Decrease",
      incrementLabel = "Increase",
      onBlur,
      ...props
    },
    ref
  ) => {
    const isControlled = value !== undefined
    const [text, setText] = React.useState(() =>
      String(value ?? defaultValue ?? "")
    )
    const parsed = text.trim() === "" ? Number.NaN : Number(text)
    /* A controlled value the text does not already spell wins over the text. */
    const shown =
      isControlled && !Number.isNaN(parsed) && parsed !== value
        ? String(value)
        : text
    const current = isControlled ? value : parsed

    const clamp = (point: number) =>
      Math.min(
        max ?? Number.POSITIVE_INFINITY,
        Math.max(min ?? Number.NEGATIVE_INFINITY, point)
      )

    const commit = (point: number) => {
      const next = Number(clamp(point).toFixed(decimalsOf(step)))
      setText(String(next))
      onValueChange?.(next)
    }

    const stepBy = (direction: 1 | -1) => {
      const from = Number.isNaN(current)
        ? (min ?? 0) - direction * step
        : current
      commit(from + direction * step)
    }

    return (
      <div
        data-invalid={invalid || undefined}
        className={cn(
          "inline-flex items-stretch overflow-hidden rounded-[var(--newt-radius-sm)] border border-newt-border bg-newt-bg-input transition-colors duration-fast ease-newt focus-within:border-newt-brand data-[invalid]:border-newt-danger group-data-[invalid]/field:border-newt-danger",
          disabled && "opacity-50",
          className
        )}
      >
        <button
          type="button"
          aria-label={decrementLabel}
          disabled={disabled || (min !== undefined && current <= min)}
          onClick={() => stepBy(-1)}
          className={stepClassName}
        >
          <svg viewBox="0 0 16 16" aria-hidden="true" className="h-3.5 w-3.5">
            <path
              fill="currentColor"
              d="M3 7h10a1 1 0 1 1 0 2H3a1 1 0 0 1 0-2Z"
            />
          </svg>
        </button>
        <input
          ref={ref}
          type="number"
          inputMode={decimalsOf(step) === 0 ? "numeric" : "decimal"}
          min={min}
          max={max}
          step={step}
          value={shown}
          disabled={disabled}
          aria-invalid={invalid || undefined}
          onChange={(event) => {
            setText(event.target.value)
            const next =
              event.target.value.trim() === ""
                ? Number.NaN
                : Number(event.target.value)
            if (!Number.isNaN(next)) onValueChange?.(next)
          }}
          onBlur={(event) => {
            onBlur?.(event)
            if (!Number.isNaN(parsed) && clamp(parsed) !== parsed) {
              commit(parsed)
            }
          }}
          className="w-16 border-0 bg-transparent px-1 py-2.5 text-center font-[family-name:var(--newt-font-sans)] text-sm tabular-nums text-newt-text-primary [appearance:textfield] focus:outline-none disabled:cursor-not-allowed [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
          {...props}
        />
        <button
          type="button"
          aria-label={incrementLabel}
          disabled={disabled || (max !== undefined && current >= max)}
          onClick={() => stepBy(1)}
          className={stepClassName}
        >
          <svg viewBox="0 0 16 16" aria-hidden="true" className="h-3.5 w-3.5">
            <path
              fill="currentColor"
              d="M8 2a1 1 0 0 1 1 1v4h4a1 1 0 1 1 0 2H9v4a1 1 0 1 1-2 0V9H3a1 1 0 0 1 0-2h4V3a1 1 0 0 1 1-1Z"
            />
          </svg>
        </button>
      </div>
    )
  }
)
NumberInput.displayName = "NumberInput"

export { NumberInput }
<script setup lang="ts">
import { computed, ref, watch, type HTMLAttributes } from "vue"

import { cn } from "@/lib/utils"

/*
 * A number field with its two steppers drawn as real buttons. The input stays
 * `type="number"`, so the arrow keys and the announced range are the
 * browser's. What is typed is kept as text until it parses, so a reader can
 * clear the field or type a minus sign on the way to a number; the value is
 * clamped to `min` and `max` when the field is left. Attributes other than
 * `class` land on the input.
 */
defineOptions({ inheritAttrs: false })

const props = withDefaults(
  defineProps<{
    class?: HTMLAttributes["class"]
    min?: number
    max?: number
    step?: number
    invalid?: boolean
    disabled?: boolean
    /** Accessible names of the two stepper buttons. */
    decrementLabel?: string
    incrementLabel?: string
  }>(),
  {
    step: 1,
    invalid: false,
    disabled: false,
    decrementLabel: "Decrease",
    incrementLabel: "Increase",
  }
)

const model = defineModel<number>()

const text = ref(model.value === undefined ? "" : String(model.value))
const parsed = computed(() =>
  text.value.trim() === "" ? Number.NaN : Number(text.value)
)

/* A value set from outside that the text does not already spell replaces it. */
watch(model, (next) => {
  if (next !== undefined && next !== parsed.value) text.value = String(next)
})

/** As many decimals as the step has, so 0.1 + 0.2 reads 0.3. */
const decimals = computed(() => {
  const spelled = String(props.step)
  const point = spelled.indexOf(".")
  return point === -1 ? 0 : spelled.length - point - 1
})

function clamp(point: number): number {
  return Math.min(
    props.max ?? Number.POSITIVE_INFINITY,
    Math.max(props.min ?? Number.NEGATIVE_INFINITY, point)
  )
}

function commit(point: number) {
  const next = Number(clamp(point).toFixed(decimals.value))
  text.value = String(next)
  model.value = next
}

function stepBy(direction: 1 | -1) {
  const from = Number.isNaN(parsed.value)
    ? (props.min ?? 0) - direction * props.step
    : parsed.value
  commit(from + direction * props.step)
}

function onInput(event: Event) {
  if (!(event.target instanceof HTMLInputElement)) return
  text.value = event.target.value
  if (!Number.isNaN(parsed.value)) model.value = parsed.value
}

function onBlur() {
  if (!Number.isNaN(parsed.value) && clamp(parsed.value) !== parsed.value) {
    commit(parsed.value)
  }
}

const stepClassName =
  "inline-flex w-9 shrink-0 items-center justify-center text-newt-text-secondary transition-colors duration-fast ease-newt hover:bg-newt-bg-hover hover:text-newt-text-primary focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-newt-text-link disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-newt-text-secondary"
</script>

<template>
  <div
    :data-invalid="props.invalid ? true : undefined"
    :class="
      cn(
        'inline-flex items-stretch overflow-hidden rounded-[var(--newt-radius-sm)] border border-newt-border bg-newt-bg-input transition-colors duration-fast ease-newt focus-within:border-newt-brand data-[invalid]:border-newt-danger group-data-[invalid]/field:border-newt-danger',
        props.disabled && 'opacity-50',
        props.class
      )
    "
  >
    <button
      type="button"
      :aria-label="props.decrementLabel"
      :disabled="
        props.disabled || (props.min !== undefined && parsed <= props.min)
      "
      :class="stepClassName"
      @click="stepBy(-1)"
    >
      <svg viewBox="0 0 16 16" aria-hidden="true" class="h-3.5 w-3.5">
        <path fill="currentColor" d="M3 7h10a1 1 0 1 1 0 2H3a1 1 0 0 1 0-2Z" />
      </svg>
    </button>
    <input
      v-bind="$attrs"
      type="number"
      :inputmode="decimals === 0 ? 'numeric' : 'decimal'"
      :min="props.min"
      :max="props.max"
      :step="props.step"
      :value="text"
      :disabled="props.disabled"
      :aria-invalid="props.invalid ? true : undefined"
      class="w-16 border-0 bg-transparent px-1 py-2.5 text-center font-[family-name:var(--newt-font-sans)] text-sm tabular-nums text-newt-text-primary [appearance:textfield] focus:outline-none disabled:cursor-not-allowed [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
      @input="onInput"
      @blur="onBlur"
    />
    <button
      type="button"
      :aria-label="props.incrementLabel"
      :disabled="
        props.disabled || (props.max !== undefined && parsed >= props.max)
      "
      :class="stepClassName"
      @click="stepBy(1)"
    >
      <svg viewBox="0 0 16 16" aria-hidden="true" class="h-3.5 w-3.5">
        <path
          fill="currentColor"
          d="M8 2a1 1 0 0 1 1 1v4h4a1 1 0 1 1 0 2H9v4a1 1 0 1 1-2 0V9H3a1 1 0 0 1 0-2h4V3a1 1 0 0 1 1-1Z"
        />
      </svg>
    </button>
  </div>
</template>
export { default as NumberInput } from "./NumberInput.vue"

Update the import paths

The files import @/lib/utils and sibling components through the aliases in your components.json. Point them at wherever those live in your project.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Number Input to your React project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Number Input to your Vue project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

Usage

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

export function Example() {
  return <NumberInput />
}
<script setup lang="ts">
import { NumberInput } from "@/components/ui/number-input"
</script>

<template>
  <NumberInput />
</template>

Examples

Decimal step

A fractional step switches the field to a decimal keyboard. The stepper buttons round the value to the step’s precision; a typed value is not rounded unless it has to be corrected to fit the range. decrementLabel and incrementLabel rename the two buttons for screen readers.

Root class newt-number
"use client"

import * as React from "react"

import { Field, FieldHelp, Label } from "@/registry/bases/newt/ui/form-fields"
import { NumberInput } from "@/registry/bases/newt/ui/number-input"

/* The value keeps as many decimals as the step has, and no more. */
export default function NumberInputDecimalDemo() {
  const [speed, setSpeed] = React.useState(1)

  return (
    <Field className="items-start">
      <Label htmlFor="newt-number-input-decimal">Playback speed</Label>
      <NumberInput
        id="newt-number-input-decimal"
        min={0.25}
        max={2}
        step={0.25}
        value={speed}
        onValueChange={setSpeed}
        decrementLabel="Slower"
        incrementLabel="Faster"
      />
      <FieldHelp>
        {speed === 1
          ? "Voice messages play at normal speed."
          : `Voice messages play at ${speed}× speed.`}
      </FieldHelp>
    </Field>
  )
}
<script setup lang="ts">
import { ref } from "vue"
import { Field, FieldHelp, Label } from "~~/registry/bases/newt/ui/form-fields"
import { NumberInput } from "~~/registry/bases/newt/ui/number-input"

/* The value keeps as many decimals as the step has, and no more. */
const speed = ref(1)
</script>

<template>
  <Field class="items-start">
    <Label for="newt-number-input-decimal">Playback speed</Label>
    <NumberInput
      id="newt-number-input-decimal"
      v-model="speed"
      :min="0.25"
      :max="2"
      :step="0.25"
      decrement-label="Slower"
      increment-label="Faster"
    />
    <FieldHelp>
      {{
        speed === 1
          ? "Voice messages play at normal speed."
          : `Voice messages play at ${speed}× speed.`
      }}
    </FieldHelp>
  </Field>
</template>

Invalid

min and max already clamp the value, so keep invalid for a rule the control cannot know. Raise the limit to 12 to clear the error.

Root class newt-number
"use client"

import * as React from "react"

import { Field, FieldHelp, Label } from "@/registry/bases/newt/ui/form-fields"
import { NumberInput } from "@/registry/bases/newt/ui/number-input"

const CONNECTED = 12

/*
 * `min` and `max` clamp what the control can say; `invalid` is for a rule the
 * control cannot know, such as how many people are already in the channel.
 */
export default function NumberInputInvalidDemo() {
  const [limit, setLimit] = React.useState(8)
  const invalid = limit < CONNECTED

  return (
    <Field className="items-start">
      <Label htmlFor="newt-number-input-invalid">User limit</Label>
      <NumberInput
        id="newt-number-input-invalid"
        min={1}
        max={99}
        value={limit}
        onValueChange={setLimit}
        invalid={invalid}
        aria-describedby="newt-number-input-invalid-help"
      />
      {invalid ? (
        <FieldHelp id="newt-number-input-invalid-help" variant="error">
          {CONNECTED} members are connected. Pick {CONNECTED} or more.
        </FieldHelp>
      ) : (
        <FieldHelp id="newt-number-input-invalid-help">
          Up to {limit} members can join this voice channel.
        </FieldHelp>
      )}
    </Field>
  )
}
<script setup lang="ts">
import { computed, ref } from "vue"
import { Field, FieldHelp, Label } from "~~/registry/bases/newt/ui/form-fields"
import { NumberInput } from "~~/registry/bases/newt/ui/number-input"

const CONNECTED = 12

/*
 * `min` and `max` clamp what the control can say; `invalid` is for a rule the
 * control cannot know, such as how many people are already in the channel.
 */
const limit = ref(8)
const invalid = computed(() => limit.value < CONNECTED)
</script>

<template>
  <Field class="items-start">
    <Label for="newt-number-input-invalid">User limit</Label>
    <NumberInput
      id="newt-number-input-invalid"
      v-model="limit"
      :min="1"
      :max="99"
      :invalid="invalid"
      aria-describedby="newt-number-input-invalid-help"
    />
    <FieldHelp
      v-if="invalid"
      id="newt-number-input-invalid-help"
      variant="error"
    >
      {{ CONNECTED }} members are connected. Pick {{ CONNECTED }} or more.
    </FieldHelp>
    <FieldHelp v-else id="newt-number-input-invalid-help">
      Up to {{ limit }} members can join this voice channel.
    </FieldHelp>
  </Field>
</template>

Disabled

disabled locks the field and both steppers at once, for a value that is shown but set somewhere else.

Root class newt-number
import { Field, FieldHelp, Label } from "@/registry/bases/newt/ui/form-fields"
import { NumberInput } from "@/registry/bases/newt/ui/number-input"

export default function NumberInputDisabledDemo() {
  return (
    <Field className="items-start">
      <Label htmlFor="newt-number-input-disabled">Upload limit (MB)</Label>
      <NumberInput id="newt-number-input-disabled" value={25} disabled />
      <FieldHelp>Raised by your server&apos;s boost level.</FieldHelp>
    </Field>
  )
}
<script setup lang="ts">
import { Field, FieldHelp, Label } from "~~/registry/bases/newt/ui/form-fields"
import { NumberInput } from "~~/registry/bases/newt/ui/number-input"
</script>

<template>
  <Field class="items-start">
    <Label for="newt-number-input-disabled">Upload limit (MB)</Label>
    <NumberInput id="newt-number-input-disabled" :model-value="25" disabled />
    <FieldHelp>Raised by your server's boost level.</FieldHelp>
  </Field>
</template>

API reference

NumberInput

PropType
value / v-model?number

The current value. In React, leave it undefined and pass `defaultValue` to let the component own it.

Typenumber
onValueChange?(value: number) => void

React only. Called whenever the text reads as a number; Vue emits `update:modelValue`.

Type(value: number) => void
min?number

The lowest value. The decrement button is disabled there.

Typenumber
max?number

The highest value. The increment button is disabled there.

Typenumber
step?number

How far one press moves the value. A fractional step sets how many decimals are kept.

Typenumber
Default1
invalid?boolean

Turns the border to the danger colour and sets `aria-invalid` on the input.

Typeboolean
Defaultfalse
disabled?boolean

Stops the field and both buttons taking input.

Typeboolean
Defaultfalse
decrementLabel?string

Accessible name of the minus button.

Typestring
Default"Decrease"
incrementLabel?string

Accessible name of the plus button.

Typestring
Default"Increase"

Every other attribute is passed to the number input. className (React) or class (Vue) lands on the wrapper, which is where a width belongs.

Accessibility

The field is a native <input type="number">, so it is announced as a spin button with its range, and Up and Down step it without the buttons. The two buttons are named by decrementLabel and incrementLabel; translate them with the rest of the interface. Name the field itself with a <label> or aria-label, and say the unit in the label or the helper text, because “15” alone does not say seconds.

decrementLabel and incrementLabel name the two stepper buttons. Translating labels lists every English default.

Tokens

Number Input reads its colours, radii and motion from the --newt-* tokens installed with the library. Override a token and every component that reads it follows, including this one — see the token layer. In the plain HTML and CSS distribution the same component is newt-number.

  • --newt-border
  • --newt-radius-sm
  • --newt-bg-input
  • --newt-duration-fast
  • --newt-ease
  • --newt-brand
  • --newt-text-primary
  • --newt-font-sans
  • --newt-text-secondary
  • --newt-bg-hover
  • --newt-text-link
  • --newt-danger