NumberField
A number field allows a user to enter a number, and increment or decrement the value using stepper buttons.
install | yarn add react-aria-components |
---|---|
version | 3.17.0 |
usage | import {NumberField} from 'react-aria-components' |
Example#
import {NumberField, Label, Group, Input, Button} from 'react-aria-components';
<NumberField defaultValue={1024} minValue={0}>
<Label>Width</Label>
<Group>
<Button slot="decrement">-</Button>
<Input />
<Button slot="increment">+</Button>
</Group>
</NumberField>
import {
Button,
Group,
Input,
Label,
NumberField
} from 'react-aria-components';
<NumberField defaultValue={1024} minValue={0}>
<Label>Width</Label>
<Group>
<Button slot="decrement">-</Button>
<Input />
<Button slot="increment">+</Button>
</Group>
</NumberField>
import {
Button,
Group,
Input,
Label,
NumberField
} from 'react-aria-components';
<NumberField
defaultValue={1024}
minValue={0}
>
<Label>Width</Label>
<Group>
<Button slot="decrement">
-
</Button>
<Input />
<Button slot="increment">
+
</Button>
</Group>
</NumberField>
Show CSS
.react-aria-NumberField {
margin-bottom: 8px;
& [role=group] {
display: flex;
width: fit-content;
border-radius: 4px;
}
& button {
background: var(--spectrum-global-color-gray-50);
border: 1px solid var(--spectrum-global-color-gray-400);
border-radius: 4px;
appearance: none;
vertical-align: middle;
font-size: 1.4rem;
width: 2.3rem;
text-align: center;
margin: 0;
outline: none;
&[slot=decrement] {
border-start-end-radius: 0;
border-end-end-radius: 0;
}
&[slot=increment] {
border-start-start-radius: 0;
border-end-start-radius: 0;
}
&[data-pressed] {
box-shadow: inset 0 1px 2px rgb(0 0 0 / 0.1);
background: var(--spectrum-global-color-gray-75);
}
}
& input {
background: var(--spectrum-global-color-gray-50);
border: 1px solid var(--spectrum-global-color-gray-400);
margin: 0 -1px;
z-index: 1;
font-size: 1rem;
padding: 6px 8px;
outline: none;
width: 6rem;
}
&:focus-within {
& input,
& button {
border-color: slateblue;
}
}
& [slot=description] {
font-size: 12px;
}
& [slot=errorMessage] {
font-size: 12px;
color: var(--spectrum-global-color-red-600);
}
}
.react-aria-NumberField {
margin-bottom: 8px;
& [role=group] {
display: flex;
width: fit-content;
border-radius: 4px;
}
& button {
background: var(--spectrum-global-color-gray-50);
border: 1px solid var(--spectrum-global-color-gray-400);
border-radius: 4px;
appearance: none;
vertical-align: middle;
font-size: 1.4rem;
width: 2.3rem;
text-align: center;
margin: 0;
outline: none;
&[slot=decrement] {
border-start-end-radius: 0;
border-end-end-radius: 0;
}
&[slot=increment] {
border-start-start-radius: 0;
border-end-start-radius: 0;
}
&[data-pressed] {
box-shadow: inset 0 1px 2px rgb(0 0 0 / 0.1);
background: var(--spectrum-global-color-gray-75);
}
}
& input {
background: var(--spectrum-global-color-gray-50);
border: 1px solid var(--spectrum-global-color-gray-400);
margin: 0 -1px;
z-index: 1;
font-size: 1rem;
padding: 6px 8px;
outline: none;
width: 6rem;
}
&:focus-within {
& input,
& button {
border-color: slateblue;
}
}
& [slot=description] {
font-size: 12px;
}
& [slot=errorMessage] {
font-size: 12px;
color: var(--spectrum-global-color-red-600);
}
}
.react-aria-NumberField {
margin-bottom: 8px;
& [role=group] {
display: flex;
width: fit-content;
border-radius: 4px;
}
& button {
background: var(--spectrum-global-color-gray-50);
border: 1px solid var(--spectrum-global-color-gray-400);
border-radius: 4px;
appearance: none;
vertical-align: middle;
font-size: 1.4rem;
width: 2.3rem;
text-align: center;
margin: 0;
outline: none;
&[slot=decrement] {
border-start-end-radius: 0;
border-end-end-radius: 0;
}
&[slot=increment] {
border-start-start-radius: 0;
border-end-start-radius: 0;
}
&[data-pressed] {
box-shadow: inset 0 1px 2px rgb(0 0 0 / 0.1);
background: var(--spectrum-global-color-gray-75);
}
}
& input {
background: var(--spectrum-global-color-gray-50);
border: 1px solid var(--spectrum-global-color-gray-400);
margin: 0 -1px;
z-index: 1;
font-size: 1rem;
padding: 6px 8px;
outline: none;
width: 6rem;
}
&:focus-within {
& input,
& button {
border-color: slateblue;
}
}
& [slot=description] {
font-size: 12px;
}
& [slot=errorMessage] {
font-size: 12px;
color: var(--spectrum-global-color-red-600);
}
}
Features#
Number fields can be built with <input type="number">
, but the behavior is very inconsistent across
browsers and platforms, it supports limited localized formatting options, and it is challenging to style
the stepper buttons. NumberField
helps achieve accessible number fields that support internationalized
formatting options and can be styled as needed.
- Customizable formatting – Support for internationalized number formatting and parsing including decimals, percentages, currency values, and units. Multiple currency formats are supported, including symbol, code, and name in standard or accounting notation.
- International – Support for the Latin, Arabic, and Han positional decimal numbering systems in over 30 locales. The numbering system is automatically detected from user input, and input method editors such as Pinyin are supported.
- Validation – Keyboard input is validated as the user types so that only numeric input is accepted, according to the locale and numbering system. Values are automatically rounded and clamped according to configurable decimal, minimum, maximum, and step values.
- Mobile friendly – An appropriate software keyboard is automatically selected based on the allowed values for ease of use.
- Accessible – Follows the spinbutton ARIA pattern, with support for arrow keys, scroll wheel, and stepper buttons to increment and decrement the value. Extensively tested across many devices and assistive technologies to ensure announcements and behaviors are consistent.
Read our blog post for more details about the interactions and internationalization support implemented by NumberField
.
Anatomy#
Number fields consist of an input element that shows the current value and allows the user to type a new value, optional stepper buttons to increment and decrement the value, a group containing the input and stepper buttons, and a label.
NumberField
also supports optional description and error message elements, which can be used
to provide more context about the field, and any validation messages. These are linked with the
input via the aria-describedby
attribute.
If there is no visual label, an aria-label
or aria-labelledby
prop must be passed instead
to identify the element to screen readers.
Composed components#
A NumberField
uses the following components, which may also be used standalone or reused in other components.
Props#
NumberField#
Name | Type | Default | Description |
decrementAriaLabel | string | — | A custom aria-label for the decrement button. If not provided, the localized string "Decrement" is used. |
incrementAriaLabel | string | — | A custom aria-label for the increment button. If not provided, the localized string "Increment" is used. |
formatOptions | Intl.NumberFormatOptions | — | Formatting options for the value displayed in the number field. This also affects what characters are allowed to be typed by the user. |
isDisabled | boolean | — | Whether the input is disabled. |
isReadOnly | boolean | — | Whether the input can be selected but not changed by the user. |
validationState | ValidationState | — | Whether the input should display its "valid" or "invalid" visual styling. |
isRequired | boolean | — | Whether user input is required on the input before form submission.
Often paired with the |
autoFocus | boolean | — | Whether the element should receive focus on render. |
value | number | — | The current value (controlled). |
defaultValue | number | — | The default value (uncontrolled). |
minValue | number | — | The smallest value allowed for the input. |
maxValue | number | — | The largest value allowed for the input. |
step | number | — | The amount that the input value changes with each increment or decrement "tick". |
children | ReactNode | (
(values: NumberFieldState
)) => ReactNode | — | |
className | string | (
(values: NumberFieldState
)) => string | — | |
style | CSSProperties | (
(values: NumberFieldState
)) => CSSProperties | — |
Events
Name | Type | Default | Description |
onFocus | (
(e: FocusEvent
)) => void | — | Handler that is called when the element receives focus. |
onBlur | (
(e: FocusEvent
)) => void | — | Handler that is called when the element loses focus. |
onFocusChange | (
(isFocused: boolean
)) => void | — | Handler that is called when the element's focus status changes. |
onKeyDown | (
(e: KeyboardEvent
)) => void | — | Handler that is called when a key is pressed. |
onKeyUp | (
(e: KeyboardEvent
)) => void | — | Handler that is called when a key is released. |
onChange | (
(value: T
)) => void | — | Handler that is called when the value changes. |
onCopy | ClipboardEventHandler<HTMLInputElement> | — | Handler that is called when the user copies text. See MDN. |
onCut | ClipboardEventHandler<HTMLInputElement> | — | Handler that is called when the user cuts text. See MDN. |
onPaste | ClipboardEventHandler<HTMLInputElement> | — | Handler that is called when the user pastes text. See MDN. |
onCompositionStart | CompositionEventHandler<HTMLInputElement> | — | Handler that is called when a text composition system starts a new text composition session. See MDN. |
onCompositionEnd | CompositionEventHandler<HTMLInputElement> | — | Handler that is called when a text composition system completes or cancels the current text composition session. See MDN. |
onCompositionUpdate | CompositionEventHandler<HTMLInputElement> | — | Handler that is called when a new character is received in the current text composition session. See MDN. |
onSelect | ReactEventHandler<HTMLInputElement> | — | Handler that is called when text in the input is selected. See MDN. |
onBeforeInput | FormEventHandler<HTMLInputElement> | — | Handler that is called when the input value is about to be modified. See MDN. |
onInput | FormEventHandler<HTMLInputElement> | — | Handler that is called when the input value is modified. See MDN. |
Accessibility
Name | Type | Default | Description |
id | string | — | The element's unique identifier. See MDN. |
aria-label | string | — | Defines a string value that labels the current element. |
aria-labelledby | string | — | Identifies the element (or elements) that labels the current element. |
aria-describedby | string | — | Identifies the element (or elements) that describes the object. |
aria-details | string | — | Identifies the element (or elements) that provide a detailed, extended description for the object. |
Label#
A <Label>
accepts all HTML attributes.
Group#
A <Group>
accepts all HTML attributes.
Input#
An <Input>
accepts all props supported by the <input>
HTML element.
Button#
A <Button>
accepts its contents as children
. Other props such as onPress
and isDisabled
will be set by the NumberField
.
Show props
Name | Type | Default | Description |
isDisabled | boolean | — | Whether the button is disabled. |
autoFocus | boolean | — | Whether the element should receive focus on render. |
type | 'button'
| 'submit'
| 'reset' | 'button' | The behavior of the button when used in an HTML form. |
children | ReactNode | (
(values: ButtonRenderProps
)) => ReactNode | — | |
className | string | (
(values: ButtonRenderProps
)) => string | — | |
style | CSSProperties | (
(values: ButtonRenderProps
)) => CSSProperties | — |
Events
Name | Type | Default | Description |
onPress | (
(e: PressEvent
)) => void | — | Handler that is called when the press is released over the target. |
onPressStart | (
(e: PressEvent
)) => void | — | Handler that is called when a press interaction starts. |
onPressEnd | (
(e: PressEvent
)) => void | — | Handler that is called when a press interaction ends, either over the target or when the pointer leaves the target. |
onPressChange | (
(isPressed: boolean
)) => void | — | Handler that is called when the press state changes. |
onPressUp | (
(e: PressEvent
)) => void | — | Handler that is called when a press is released over the target, regardless of whether it started on the target or not. |
onFocus | (
(e: FocusEvent
)) => void | — | Handler that is called when the element receives focus. |
onBlur | (
(e: FocusEvent
)) => void | — | Handler that is called when the element loses focus. |
onFocusChange | (
(isFocused: boolean
)) => void | — | Handler that is called when the element's focus status changes. |
onKeyDown | (
(e: KeyboardEvent
)) => void | — | Handler that is called when a key is pressed. |
onKeyUp | (
(e: KeyboardEvent
)) => void | — | Handler that is called when a key is released. |
Layout
Name | Type | Default | Description |
slot | string | — |
Accessibility
Name | Type | Default | Description |
id | string | — | The element's unique identifier. See MDN. |
excludeFromTabOrder | boolean | — | Whether to exclude the element from the sequential tab order. If true, the element will not be focusable via the keyboard by tabbing. This should be avoided except in rare scenarios where an alternative means of accessing the element or its functionality via the keyboard is available. |
aria-expanded | boolean
| 'true'
| 'false' | — | Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. |
aria-haspopup | boolean
| 'menu'
| 'listbox'
| 'tree'
| 'grid'
| 'dialog'
| 'true'
| 'false' | — | Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element. |
aria-controls | string | — | Identifies the element (or elements) whose contents or presence are controlled by the current element. |
aria-pressed | boolean
| 'true'
| 'false'
| 'mixed' | — | Indicates the current "pressed" state of toggle buttons. |
aria-label | string | — | Defines a string value that labels the current element. |
aria-labelledby | string | — | Identifies the element (or elements) that labels the current element. |
aria-describedby | string | — | Identifies the element (or elements) that describes the object. |
aria-details | string | — | Identifies the element (or elements) that provide a detailed, extended description for the object. |
Styling#
React Aria components can be styled in many ways, including using CSS classes, inline styles, utility classes (e.g. Tailwind), CSS-in-JS (e.g. Styled Components), etc. By default, all components include a builtin className
attribute which can be targeted using CSS selectors. These follow the react-aria-ComponentName
naming convention.
.react-aria-NumberField {
/* ... */
}
.react-aria-NumberField {
/* ... */
}
.react-aria-NumberField {
/* ... */
}
A custom className
can also be specified on any component. This overrides the default className
provided by React Aria with your own.
<NumberField className="my-number-field">
{/* ... */}
</NumberField>
<NumberField className="my-number-field">
{/* ... */}
</NumberField>
<NumberField className="my-number-field">
{/* ... */}
</NumberField>;
In addition, some components support multiple UI states (e.g. focused, placeholder, readonly, etc.). React Aria components expose states using DOM attributes, which you can target in CSS selectors. These are ARIA attributes wherever possible, or data attributes when a relevant ARIA attribute does not exist. For example:
.react-aria-Button[data-pressed] {
/* ... */
}
.react-aria-Button[data-pressed] {
/* ... */
}
.react-aria-Button[data-pressed] {
/* ... */
}
The className
and style
props also accept functions which receive states for styling. This lets you dynamically determine the classes or styles to apply, which is useful when using utility CSS libraries like Tailwind.
<Button
className={({ isPressed }) => isPressed ? 'bg-gray-700' : 'bg-gray-600'}
/>;
<Button
className={({ isPressed }) =>
isPressed ? 'bg-gray-700' : 'bg-gray-600'}
/>;
<Button
className={(
{ isPressed }
) =>
isPressed
? 'bg-gray-700'
: 'bg-gray-600'}
/>;
The states, selectors, and render props for each component used in a NumberField
are documented below.
NumberField#
A NumberField
can be targeted with the .react-aria-NumberField
CSS selector, or by overriding with a custom className
. It provides a NumberFieldState
object to its render props, which can be used to customize the className
, style
, or children
.
Label#
A Label
can be targeted with the .react-aria-Label
CSS selector, or by overriding with a custom className
.
Group#
A Group
can be targeted with the [role=group]
selector, or by adding a custom className
.
Input#
An Input
can be targeted with the input
CSS selector, or by adding a custom className
. It supports standard CSS pseudo classes such as :focus
for states. See MDN for details.
Button#
A Button can be targeted with the button
CSS selector, or by adding a custom className
. Within a NumberField
, there are two slots, which can be targeted with the [slot=increment]
and [slot=decrement]
CSS selectors. Buttons support the following states:
Name | CSS Selector | Description |
isHovered | [data-hovered] | Whether the button is currently hovered with a mouse. |
isPressed | [data-pressed] | Whether the button is currently in a pressed state. |
isFocused | :focus | Whether the button is focused, either via a mouse or keyboard. |
isFocusVisible | [data-focus-visible] | Whether the button is keyboard focused. |
isDisabled | :disabled | Whether the button is disabled. |
Text#
The help text elements within a NumberField
can be targeted with the [slot=description]
and [slot=errorMessage]
CSS selectors, or by adding a custom className
.
Reusable wrappers#
If you will use a NumberField in multiple places in your app, you can wrap all of the pieces into a reusable component. This way, the DOM structure, styling code, and other logic are defined in a single place and reused everywhere to ensure consistency.
This example wraps NumberField
and all of its children together into a single component which accepts a label
prop, which is passed to the right place. It also shows how to use the description
and errorMessage
slots to render help text (see below for details).
import {Text} from 'react-aria-components';
function MyNumberField({label, description, errorMessage, ...props}) {
return (
<NumberField {...props}>
<Label>{label}</Label>
<Group>
<Button slot="decrement">-</Button>
<Input />
<Button slot="increment">+</Button>
</Group>
{description && <Text slot="description">{description}</Text>}
{errorMessage && <Text slot="errorMessage">{errorMessage}</Text>}
</NumberField>
);
}
<MyNumberField label="Cookies" />
import {Text} from 'react-aria-components';
function MyNumberField(
{ label, description, errorMessage, ...props }
) {
return (
<NumberField {...props}>
<Label>{label}</Label>
<Group>
<Button slot="decrement">-</Button>
<Input />
<Button slot="increment">+</Button>
</Group>
{description && (
<Text slot="description">{description}</Text>
)}
{errorMessage && (
<Text slot="errorMessage">{errorMessage}</Text>
)}
</NumberField>
);
}
<MyNumberField label="Cookies" />
import {Text} from 'react-aria-components';
function MyNumberField(
{
label,
description,
errorMessage,
...props
}
) {
return (
<NumberField
{...props}
>
<Label>
{label}
</Label>
<Group>
<Button slot="decrement">
-
</Button>
<Input />
<Button slot="increment">
+
</Button>
</Group>
{description && (
<Text slot="description">
{description}
</Text>
)}
{errorMessage && (
<Text slot="errorMessage">
{errorMessage}
</Text>
)}
</NumberField>
);
}
<MyNumberField label="Cookies" />
Usage#
The following examples show how to use the MyNumberField
component created in the above example.
Controlled#
By default, NumberField
is uncontrolled. However, when using the value
prop, it becomes controlled.
This allows you to store the current value in your own state, and use it elsewhere.
The onChange
event is triggered whenever the number value updates. This happens when the user types a
value and blurs the input, or when incrementing or decrementing the value. It does not happen as the user
types because partial input may not be parseable to a valid number.
function Example() {
let [value, setValue] = React.useState(6);
return (
<>
<MyNumberField
label="Controlled value"
value={value}
onChange={setValue} />
<div>Current value prop: {value}</div>
</>
);
}
function Example() {
let [value, setValue] = React.useState(6);
return (
<>
<MyNumberField
label="Controlled value"
value={value}
onChange={setValue} />
<div>Current value prop: {value}</div>
</>
);
}
function Example() {
let [value, setValue] =
React.useState(6);
return (
<>
<MyNumberField
label="Controlled value"
value={value}
onChange={setValue}
/>
<div>
Current value
prop: {value}
</div>
</>
);
}
Decimals#
The default formatting style for NumberField
is decimal, but you can configure various aspects via the formatOptions
prop. All options supported by Intl.NumberFormat
are supported, including configuration of minimum and maximum fraction digits, sign display, grouping separators, etc.
Currently only standard notation is supported, though scientific, engineering, and compact notation may be supported in the future.
The following example uses the signDisplay
option to include the plus sign for positive numbers, for example to display
an offset from some value. In addition, it always displays a minimum of 1 digit after the decimal point, and allows up to
2 fraction digits. If the user enters more than 2 fraction digits, the result will be rounded.
<MyNumberField
label="Adjust exposure"
defaultValue={0}
formatOptions={{
signDisplay: 'exceptZero',
minimumFractionDigits: 1,
maximumFractionDigits: 2
}} />
<MyNumberField
label="Adjust exposure"
defaultValue={0}
formatOptions={{
signDisplay: 'exceptZero',
minimumFractionDigits: 1,
maximumFractionDigits: 2
}} />
<MyNumberField
label="Adjust exposure"
defaultValue={0}
formatOptions={{
signDisplay:
'exceptZero',
minimumFractionDigits:
1,
maximumFractionDigits:
2
}}
/>
Percentages#
The style: 'percent'
option can be passed to the formatOptions
prop to treat the value as a percentage. In this mode,
the value is multiplied by 100 before it is displayed, i.e. 0.45
is displayed as 45%
. The reverse is also true: when the
user enters a value, the onChange
event will be triggered with the entered value divided by 100. When the percent option
is enabled, the default step automatically changes to 0.01
such that incrementing and decrementing occurs by 1%
. This can
be overridden with the step
prop. See below for details.
<MyNumberField
label="Sales tax"
defaultValue={0.05}
formatOptions={{
style: 'percent'
}} />
<MyNumberField
label="Sales tax"
defaultValue={0.05}
formatOptions={{
style: 'percent'
}} />
<MyNumberField
label="Sales tax"
defaultValue={0.05}
formatOptions={{
style: 'percent'
}} />
Currency values#
The style: 'currency'
option can be passed to the formatOptions
prop to treat the value as a currency value. The currency
option must also be passed to set the currency code (e.g. USD
) to use. In addition, the currencyDisplay
option can be
used to choose whether to display the currency symbol, currency code, or currency name. Finally, the currencySign
option
can be set to accounting
to use accounting notation for negative numbers, which uses parentheses rather than a minus sign
in some locales.
If you need to allow the user to change the currency, you should include a separate dropdown next to the number field. The number field itself will not determine the currency from the user input.
<MyNumberField
label="Transaction amount"
defaultValue={45}
formatOptions={{
style: 'currency',
currency: 'EUR',
currencyDisplay: 'code',
currencySign: 'accounting'
}} />
<MyNumberField
label="Transaction amount"
defaultValue={45}
formatOptions={{
style: 'currency',
currency: 'EUR',
currencyDisplay: 'code',
currencySign: 'accounting'
}} />
<MyNumberField
label="Transaction amount"
defaultValue={45}
formatOptions={{
style: 'currency',
currency: 'EUR',
currencyDisplay:
'code',
currencySign:
'accounting'
}}
/>
Units#
The style: 'unit'
option can be passed to the formatOptions
prop to format the value with a unit of measurement. The unit
option must also be passed to set which unit to use (e.g. inch
). In addition, the unitDisplay
option can be used to choose
whether to display the unit in long, short, or narrow format.
If you need to allow the user to change the unit, you should include a separate dropdown next to the number field. The number field itself will not determine the unit from the user input.
Note: the unit style is not currently supported in Safari. A polyfill may be necessary.
<MyNumberField
label="Package width"
defaultValue={4}
formatOptions={{
style: 'unit',
unit: 'inch',
unitDisplay: 'long'
}} />
<MyNumberField
label="Package width"
defaultValue={4}
formatOptions={{
style: 'unit',
unit: 'inch',
unitDisplay: 'long'
}} />
<MyNumberField
label="Package width"
defaultValue={4}
formatOptions={{
style: 'unit',
unit: 'inch',
unitDisplay: 'long'
}} />
Minimum and maximum values#
The minValue
and maxValue
props can be used to limit the entered value to a specific range. The value will be clamped
when the user blurs the input field. In addition, the increment and decrement buttons will be disabled when the value is
within one step
value from the bounds (see below for info about steps). Ranges can be open ended by only
providing either minValue
or maxValue
rather than both.
If a valid range is known ahead of time, it is a good idea to provide it to NumberField
so it can optimize the experience.
For example, when the minimum value is greater than or equal to zero, it is possible to use a numeric keyboard on iOS rather
than a full text keyboard (necessary to enter a minus sign).
<MyNumberField
label="Enter your age"
minValue={0} />
<MyNumberField
label="Enter your age"
minValue={0} />
<MyNumberField
label="Enter your age"
minValue={0} />
Step values#
The step
prop can be used to snap the value to certain increments. If there is a minValue
defined, the steps are calculated
starting from the minimum. For example, if minValue={2}
, and step={3}
, the valid step values would be 2, 5, 8, 11, etc. If no
minValue
is defined, the steps are calculated starting from zero and extending in both directions. In other words, such that the
values are evenly divisible by the step. If no step
is defined, any decimal value may be typed, but incrementing and decrementing
snaps the value to an integer.
If the user types a value that is between two steps and blurs the input, the value will be snapped to the nearest step. When
incrementing or decrementing, the value is snapped to the nearest step that is higher or lower, respectively.
When incrementing or decrementing from an empty field, the value starts at the minValue
or maxValue
, respectively, if defined.
Otherwise, the value starts from 0
.
<MyNumberField
label="Step"
step={10} />
<MyNumberField
label="Step + minValue"
minValue={2}
step={3} />
<MyNumberField
label="Step + minValue + maxValue"
minValue={2}
maxValue={21}
step={3} />
<MyNumberField
label="Step"
step={10} />
<MyNumberField
label="Step + minValue"
minValue={2}
step={3} />
<MyNumberField
label="Step + minValue + maxValue"
minValue={2}
maxValue={21}
step={3} />
<MyNumberField
label="Step"
step={10}
/>
<MyNumberField
label="Step + minValue"
minValue={2}
step={3}
/>
<MyNumberField
label="Step + minValue + maxValue"
minValue={2}
maxValue={21}
step={3}
/>
Disabled and read only#
The isDisabled
and isReadOnly
props can be used prevent the user from editing the value of the number field.
The difference is that isReadOnly
still allows the input to be focused, while isDisabled
prevents all user interaction.
<MyNumberField label="Disabled" isDisabled value={25} />
<MyNumberField label="Read only" isReadOnly value={32} />
<MyNumberField label="Disabled" isDisabled value={25} />
<MyNumberField label="Read only" isReadOnly value={32} />
<MyNumberField
label="Disabled"
isDisabled
value={25}
/>
<MyNumberField
label="Read only"
isReadOnly
value={32}
/>
Help text#
The description
slot can be used to associate additional help text with a number field. Additionally, the errorMessage
slot can be used to help the user fix a validation error. It should be combined with the validationState
prop to semantically mark the number field as invalid for assistive technologies.
function Example() {
let [value, setValue] = React.useState(1);
let isValid = React.useMemo(() => value > 0 || value === NaN, [value]);
return (
<MyNumberField
validationState={value === NaN
? undefined
: (isValid ? 'valid' : 'invalid')}
value={value}
onChange={setValue}
label="Positive numbers only"
description={isValid ? 'Enter a positive number.' : null}
errorMessage={isValid
? null
: value === 0
? 'Is zero positive?'
: 'Positive numbers are bigger than 0.'}
/>
);
}
function Example() {
let [value, setValue] = React.useState(1);
let isValid = React.useMemo(
() => value > 0 || value === NaN,
[value]
);
return (
<MyNumberField
validationState={value === NaN
? undefined
: (isValid ? 'valid' : 'invalid')}
value={value}
onChange={setValue}
label="Positive numbers only"
description={isValid
? 'Enter a positive number.'
: null}
errorMessage={isValid
? null
: value === 0
? 'Is zero positive?'
: 'Positive numbers are bigger than 0.'}
/>
);
}
function Example() {
let [value, setValue] =
React.useState(1);
let isValid = React
.useMemo(
() =>
value > 0 ||
value === NaN,
[value]
);
return (
<MyNumberField
validationState={value ===
NaN
? undefined
: (isValid
? 'valid'
: 'invalid')}
value={value}
onChange={setValue}
label="Positive numbers only"
description={isValid
? 'Enter a positive number.'
: null}
errorMessage={isValid
? null
: value === 0
? 'Is zero positive?'
: 'Positive numbers are bigger than 0.'}
/>
);
}
Advanced customization#
Composition#
If you need to customize one of the components within a NumberField
, such as Label
or Input
, in many cases you can create a wrapper component. This lets you customize the props passed to the component.
function MyInput(props) {
return <MyInput {...props} className="my-input" />
}
function MyInput(props) {
return <MyInput {...props} className="my-input" />
}
function MyInput(props) {
return (
<MyInput
{...props}
className="my-input"
/>
);
}
Hooks#
If you need to customize things even further, such as accessing internal state or customizing DOM structure, you can drop down to the lower level Hook-based API. See useNumberField for more details.