packages/react-aria-components/docs/NumberField.mdx
{/* Copyright 2020 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */}
import {Layout} from '@react-spectrum/docs'; export default Layout;
import docs from 'docs:react-aria-components'; import statelyDocs from 'docs:@react-stately/numberfield'; import {PropTable, HeaderInfo, TypeLink, PageDescription, StateTable, ContextTable} from '@react-spectrum/docs'; import styles from '@react-spectrum/docs/src/docs.css'; import packageData from 'react-aria-components/package.json'; import Anatomy from '/packages/react-aria/docs/numberfield/anatomy.svg'; import ChevronRight from '@spectrum-icons/workflow/ChevronRight'; import {Divider} from '@react-spectrum/divider'; import {ExampleCard} from '@react-spectrum/docs/src/ExampleCard'; import Label from '@react-spectrum/docs/pages/assets/component-illustrations/Label.svg'; import Button from '@react-spectrum/docs/pages/assets/component-illustrations/ActionButton.svg'; import Input from '@react-spectrum/docs/pages/assets/component-illustrations/Input.svg'; import Form from '@react-spectrum/docs/pages/assets/component-illustrations/Form.svg'; import {StarterKits} from '@react-spectrum/docs/src/StarterKits';
<PageDescription>{docs.exports.NumberField.description}</PageDescription>
<HeaderInfo packageData={packageData} componentNames={['NumberField']} sourceData={[ {type: 'W3C', url: 'https://www.w3.org/WAI/ARIA/apg/patterns/spinbutton/'} ]} />
import {NumberField, Label, Group, Input, Button} from 'react-aria-components';
import {Plus, Minus} from 'lucide-react';
<NumberField defaultValue={1024} minValue={0}>
<Label>Width</Label>
<Group>
<Button slot="decrement"><Minus size={18} /></Button>
<Input />
<Button slot="increment"><Plus size={18} /></Button>
</Group>
</NumberField>
@import './Button.mdx' layer(button);
@import './Form.mdx' layer(form);
@import "@react-aria/example-theme";
.react-aria-NumberField {
margin-bottom: 8px;
color: var(--text-color);
.react-aria-Group {
display: flex;
width: fit-content;
border-radius: 4px;
&[data-focus-within] {
outline: 1px solid var(--focus-ring-color);
.react-aria-Input,
.react-aria-Button {
border-color: var(--focus-ring-color);
}
}
}
.react-aria-Button {
font-size: 1.4rem;
width: 2.3rem;
padding: 0;
display: inline-flex;
align-items: center;
justify-content: center;
&[slot=decrement] {
border-start-end-radius: 0;
border-end-end-radius: 0;
}
&[slot=increment] {
border-start-start-radius: 0;
border-end-start-radius: 0;
}
}
.react-aria-Input {
background: var(--field-background);
border: 1px solid var(--border-color);
border-radius: 0;
color: var(--field-text-color);
margin: 0 -1px;
z-index: 1;
font-size: 1rem;
padding: 0.429rem 0.571rem;
outline: none;
width: 6rem;
flex: 1;
}
}
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.
Read our blog post for more details about the interactions and internationalization support implemented by NumberField.
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.
import {NumberField, Label, Group, Input, Button, Text, FieldError} from 'react-aria-components';
<NumberField>
<Label />
<Group>
<Input />
<Button slot="increment" />
<Button slot="decrement" />
</Group>
<Text slot="description" />
<FieldError />
</NumberField>
If there is no visual label, an aria-label or aria-labelledby prop must be passed instead
to identify the element to screen readers.
NumberField makes use of the following concepts:
<ExampleCard url="forms.html" title="Forms" description="Validating and submitting form data, and integrating with form libraries.">
<Form /> </ExampleCard> </section>A NumberField uses the following components, which may also be used standalone or reused in other components.
<ExampleCard url="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label" title="Label" description="A label provides context for an input element."> <Label /> </ExampleCard>
<ExampleCard url="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input" title="Input" description="An input allows a user to enter a plain text value with a keyboard."> <Input /> </ExampleCard>
<ExampleCard url="Button.html" title="Button" description="A button allows a user to perform an action."> <Button /> </ExampleCard>
</section>To help kick-start your project, we offer starter kits that include example implementations of all React Aria components with various styling solutions. All components are fully styled, including support for dark mode, high contrast mode, and all UI states. Each starter comes with a pre-configured Storybook that you can experiment with, or use as a starting point for your own component library.
<StarterKits component="numberfield" />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 slot to render help text, and FieldError component to render validation errors.
import type {NumberFieldProps, ValidationResult} from 'react-aria-components';
import {Text, FieldError} from 'react-aria-components';
interface MyNumberFieldProps extends NumberFieldProps {
label?: string,
description?: string,
errorMessage?: string | ((validation: ValidationResult) => string)
}
function MyNumberField({label, description, errorMessage, ...props}: MyNumberFieldProps) {
return (
<NumberField {...props}>
<Label>{label}</Label>
<Group>
<Button slot="decrement"><Minus size={18} /></Button>
<Input />
<Button slot="increment"><Plus size={18} /></Button>
</Group>
{description && <Text slot="description">{description}</Text>}
<FieldError>{errorMessage}</FieldError>
</NumberField>
);
}
<MyNumberField label="Cookies" />
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>
</>
);
}
NumberField supports the name prop for integration with HTML forms. The value will be submitted to the server as a raw number (e.g. 45), not as a locale-dependent formatted string (e.g. "$45.00").
<MyNumberField
label="Transaction amount"
/*- begin highlight -*/
name="amount"
/*- end highlight -*/
defaultValue={45}
formatOptions={{
style: 'currency',
currency: 'USD'
}} />
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
}} />
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'
}} />
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'
}} />
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'
}} />
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} />
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} />
NumberField supports the isRequired prop to ensure the user enters a value, as well as custom validation functions, realtime validation, and server-side validation. It can also be integrated with other form libraries. See the Forms guide to learn more.
To display validation errors, add a <FieldError> element as a child of the NumberField. This allows you to render error messages from all of the above sources with consistent custom styles.
import {Form, FieldError} from 'react-aria-components';
<Form>
<NumberField name="width" isRequired>
<Label>Width</Label>
<Group>
<Button slot="decrement"><Minus size={18} /></Button>
<Input />
<Button slot="increment"><Plus size={18} /></Button>
</Group>
<FieldError />
</NumberField>
<Button type="submit">Submit</Button>
</Form>
.react-aria-NumberField {
&[data-invalid] {
.react-aria-Input,
.react-aria-Button {
border-color: var(--invalid-color);
}
&:focus-within {
.react-aria-Input,
.react-aria-Button {
border-color: var(--focus-ring-color);
}
}
}
.react-aria-FieldError {
font-size: 12px;
color: var(--invalid-color);
}
}
By default, FieldError displays default validation messages provided by the browser. See Customizing error messages in the Forms guide to learn how to provide your own custom errors.
The description slot can be used to associate additional help text with a number field.
<NumberField>
<Label>Width</Label>
<Group>
<Button slot="decrement"><Minus size={18} /></Button>
<Input />
<Button slot="increment"><Plus size={18} /></Button>
</Group>
<Text slot="description">Enter a width in centimeters.</Text>
</NumberField>
.react-aria-NumberField {
[slot=description] {
font-size: 12px;
}
}
The isDisabled prop can be used prevent the user from editing the value of the number field.
<MyNumberField label="Disabled" isDisabled value={25} />
.react-aria-NumberField {
.react-aria-Button {
&[data-disabled] {
border-color: var(--border-color-disabled);
color: var(--text-color-disabled);
}
}
.react-aria-Input {
&[data-disabled] {
border-color: var(--border-color-disabled);
color: var(--text-color-disabled);
}
}
}
The isReadOnly prop makes the NumberField's value immutable. Unlike isDisabled, the NumberField remains focusable
and the contents can still be copied. See the MDN docs for more information.
<MyNumberField label="Read only" isReadOnly value={32} />
A <Label> accepts all HTML attributes.
A <Group> accepts all HTML attributes.
An <Input> accepts all props supported by the <input> HTML element.
A <Button> accepts its contents as children. Other props such as onPress and isDisabled will be set by the NumberField.
A <FieldError> displays validation errors.
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 {
/* ... */
}
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>
In addition, some components support multiple UI states (e.g. focused, placeholder, readonly, etc.). React Aria components expose states using data attributes, which you can target in CSS selectors. For example:
.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'} />
The states, selectors, and render props for each component used in a NumberField are documented below.
A NumberField can be targeted with the .react-aria-NumberField CSS selector, or by overriding with a custom className. It supports the following states:
A Label can be targeted with the .react-aria-Label CSS selector, or by overriding with a custom className.
A Group can be targeted with the .react-aria-Group selector, or by overriding with a custom className. It supports the following states:
An Input can be targeted with the .react-aria-Input CSS selector, or by overriding with a custom className. It supports the following states:
A Button can be targeted with the .react-aria-Button CSS selector, or by overriding with 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:
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.
A FieldError can be targeted with the .react-aria-FieldError CSS selector, or by overriding with a custom className. It supports the following render props:
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 <Input {...props} className="my-input" />
}
All React Aria Components export a corresponding context that can be used to send props to them from a parent element. This enables you to build your own compositional APIs similar to those found in React Aria Components itself. You can send any prop or ref via context that you could pass to the corresponding component. The local props and ref on the component are merged with the ones passed via context, with the local props taking precedence (following the rules documented in mergeProps).
<ContextTable components={['NumberField']} docs={docs} />
This example shows a FieldGroup component that renders a group of number fields with a title. The entire group can be marked as read only via the isReadOnly prop, which is passed to all child number fields via the NumberFieldContext provider.
import {NumberFieldContext} from 'react-aria-components';
interface FieldGroupProps {
title?: string,
children?: React.ReactNode,
isReadOnly?: boolean
}
function FieldGroup({title, children, isReadOnly}: FieldGroupProps) {
return (
<fieldset>
<legend>{title}</legend>
<NumberFieldContext.Provider value={{isReadOnly}}>
{children}
</NumberFieldContext.Provider>
</fieldset>
);
}
<FieldGroup title="Dimensions" isReadOnly>
<MyNumberField label="Width" defaultValue={1024} />
<MyNumberField label="Height" defaultValue={768} />
</FieldGroup>
fieldset {
padding: 1.5em;
width: fit-content;
}
NumberField passes props to its child components, such as the label and input, via their associated contexts. These contexts are exported so you can also consume them in your own custom components. This enables you to reuse existing components from your app or component library together with React Aria Components.
<ContextTable components={['Label', 'Group', 'Input', 'Button', 'Text']} docs={docs} />
This example consumes from LabelContext in an existing styled label component to make it compatible with React Aria Components. The <TypeLink links={docs.links} type={docs.exports.useContextProps} /> hook merges the local props and ref with the ones provided via context by NumberField.
import type {LabelProps} from 'react-aria-components';
import {LabelContext, useContextProps} from 'react-aria-components';
const MyCustomLabel = React.forwardRef((props: LabelProps, ref: React.ForwardedRef<HTMLLabelElement>) => {
// Merge the local props and ref with the ones provided via context.
///- begin highlight -///
[props, ref] = useContextProps(props, ref, LabelContext);
///- end highlight -///
// ... your existing Label component
return <label {...props} ref={ref} />;
});
Now you can use MyCustomLabel within a NumberField, in place of the builtin React Aria Components Label.
<NumberField>
<MyCustomLabel>Value</MyCustomLabel>
<Group>
<Button slot="decrement"><Minus size={18} /></Button>
<Input />
<Button slot="increment"><Plus size={18} /></Button>
</Group>
</NumberField>
NumberField provides a <TypeLink links={statelyDocs.links} type={statelyDocs.exports.NumberFieldState} /> object to its children via NumberFieldStateContext. This can be used to access and manipulate the NumberField's state.
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.