Number Input
The NumberInput component is similar to the Input component, but it has controls for incrementing or decrementing numeric values.
Import#
Chakra UI exports 5 components for the NumberInput.
NumberInput
: The wrapper that provides context and logic to the components.NumberInputField
: Theinput
field itself.NumberInputStepper
: The wrapper for the input's stepper buttons.NumberIncrementStepper
: The button to increment the value of the input.NumberDecrementStepper
: The button to decrement the value of the input.
import {NumberInput,NumberInputField,NumberInputStepper,NumberIncrementStepper,NumberDecrementStepper,} from '@chakra-ui/react'
Usage#
The NumberInput component follows the WAI-ARIA authoring practices for the spin button widget. It is composed of smaller components to give you control of the styling of each part.
<NumberInput><NumberInputField /><NumberInputStepper><NumberIncrementStepper /><NumberDecrementStepper /></NumberInputStepper></NumberInput>
Setting a minimum and maximum value#
Pass the min
prop or max
prop to set an upper and lower limit for the input.
By default, the input will restrict the value to stay within the specified
range.
These props defaults to Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER . If they do not match your requirements you can use other
Number
properties asmin
ormax
.
<NumberInput defaultValue={15} min={10} max={20}><NumberInputField /><NumberInputStepper><NumberIncrementStepper /><NumberDecrementStepper /></NumberInputStepper></NumberInput>
Setting the step size#
Pass the step
prop to change the step size when you increment or decrement the
value. By default, the value is rounded to match the number of decimals in the
step
.
<NumberInput step={5} defaultValue={15} min={10} max={30}><NumberInputField /><NumberInputStepper><NumberIncrementStepper /><NumberDecrementStepper /></NumberInputStepper></NumberInput>
Adjusting the precision of the value#
In some cases, you might need the value to be rounded to specific decimal
points. Simply pass the precision
prop and set it to the number of decimal
points.
<NumberInput defaultValue={15} precision={2} step={0.2}><NumberInputField /><NumberInputStepper><NumberIncrementStepper /><NumberDecrementStepper /></NumberInputStepper></NumberInput>
Clamp value when user blurs the input#
In most cases, users can type custom values in the input field. If the typed
value is greater than the max
, the value is reset to max
when the user blur
out of the input.
To disable this behavior, pass clampValueOnBlur
and set to false
.
In this example, try to type a value greater than the max. It won't reset the value on blur.
<NumberInput defaultValue={15} max={30} clampValueOnBlur={false}><NumberInputField /><NumberInputStepper><NumberIncrementStepper /><NumberDecrementStepper /></NumberInputStepper></NumberInput>
Allowing out of range values#
In some scenarios, you might not want to block out of range values. Pass the
keepWithinRange
and clampValueOnBlur
props and set them to false
to
support this use case.
The NumberInput will be set
invalid
totrue
internally when the value is out of range. Out of range means that thevalue
is great thanmax
or less thanmin
.
<NumberInputdefaultValue={15}max={10}keepWithinRange={false}clampValueOnBlur={false}><NumberInputField /><NumberInputStepper><NumberIncrementStepper /><NumberDecrementStepper /></NumberInputStepper></NumberInput>
Formatting and Parsing the value#
function Example() {const format = (val) => `$` + valconst parse = (val) => val.replace(/^\$/, '')const [value, setValue] = React.useState('1.53')return (<NumberInputonChange={(valueString) => setValue(parse(valueString))}value={format(value)}max={50}><NumberInputField /><NumberInputStepper><NumberIncrementStepper /><NumberDecrementStepper /></NumberInputStepper></NumberInput>)}
Changing the size of the input#
Like the Input
component, you can pass the size
prop to change the size of
the input.
<Stack shouldWrapChildren direction='row'><NumberInput size='xs' maxW={16} defaultValue={15} min={10}><NumberInputField /><NumberInputStepper><NumberIncrementStepper /><NumberDecrementStepper /></NumberInputStepper></NumberInput><NumberInput size='sm' maxW={20} defaultValue={15} min={10}><NumberInputField /><NumberInputStepper><NumberIncrementStepper /><NumberDecrementStepper /></NumberInputStepper></NumberInput><NumberInput size='md' maxW={24} defaultValue={15} min={10}><NumberInputField /><NumberInputStepper><NumberIncrementStepper /><NumberDecrementStepper /></NumberInputStepper></NumberInput><NumberInput size='lg' maxW={32} defaultValue={15} min={10}><NumberInputField /><NumberInputStepper><NumberIncrementStepper /><NumberDecrementStepper /></NumberInputStepper></NumberInput></Stack>
Changing the styles#
You can change the style of any part of the components using style props. You can also change the icons used in the steppers.
<NumberInput size='sm' defaultValue={15} min={10}><NumberInputField focusBorderColor='red.200' /><NumberInputStepper><NumberIncrementStepperbg='green.200'_active={{ bg: 'green.300' }}children='+'/><NumberDecrementStepperbg='pink.200'_active={{ bg: 'pink.300' }}children='-'/></NumberInputStepper></NumberInput>
Combining it with a Slider#
A common use case is to combine the NumberInput
with a Slider
.
We recommend disabling focusThumbOnChange
on the Slider
, so the
NumberInput
won't lose focus after input.
Here's an example of how to do that:
function SliderInput() {const [value, setValue] = React.useState(0)const handleChange = (value) => setValue(value)return (<Flex><NumberInput maxW='100px' mr='2rem' value={value} onChange={handleChange}><NumberInputField /><NumberInputStepper><NumberIncrementStepper /><NumberDecrementStepper /></NumberInputStepper></NumberInput><Sliderflex='1'focusThumbOnChange={false}value={value}onChange={handleChange}><SliderTrack><SliderFilledTrack /></SliderTrack><SliderThumb fontSize='sm' boxSize='32px' children={value} /></Slider></Flex>)}
Create a mobile spinner#
Sometimes, you might need to create a mobile version of the number input. Here's
how you can leverage the useNumberInput
hook to build one.
function HookUsage() {const { getInputProps, getIncrementButtonProps, getDecrementButtonProps } =useNumberInput({step: 0.01,defaultValue: 1.53,min: 1,max: 6,precision: 2,})const inc = getIncrementButtonProps()const dec = getDecrementButtonProps()const input = getInputProps()return (<HStack maxW='320px'><Button {...inc}>+</Button><Input {...input} /><Button {...dec}>-</Button></HStack>)}
Increment value using Mouse wheel#
The NumberInput
component supports the ability to increment or decrement
values using the mouse wheel events. To activate this, pass the
allowMouseWheel
prop.
function MouseWheelExample() {return (<NumberInput allowMouseWheel><NumberInputField /><NumberInputStepper><NumberIncrementStepper /><NumberDecrementStepper /></NumberInputStepper></NumberInput>)}
Accessibility#
Aria Roles#
- The input has
role
set tospinbutton
to denote that users are to select from a range of discrete values using an up and down arrows on the keyboard. - The input has
aria-valuemin
set to the minimum value allowed for the spinbutton. - The input has
aria-valuemax
set to the maximum value allowed for the spinbutton. attribute should be applied to the spinbutton. - The input has
aria-valuenow
set to the current value of theinput
. - The custom spinner (up and down buttons) has
aria-hidden
set totrue
to make them invisible to screen readers.
Keyboard Navigation#
- When you hit the ⬆ or ⬇ key, the input value will be
increased or decreased by
step
. - Holding down Shift and pressing ⬆ or ⬇ will
update the value by
10 * step
. - Holding down Ctrl or ⌘, and pressing ⬆ or
⬆ will update the value by
0.1 * step
. - Long pressing the up and down stepper buttons will update the value at intervals.
Props#
NumberInput Props#
NumberInput composes Flex
with some additional props listed below.
NumberInputField Props#
NumberInputField
composes Input
so you can pass all Input
props. If you
want to change the size, pass the size
prop to the NumberInput
component
instead, as demonstrated above.
NumberInputStepper Props#
NumberInputStepper
composes Flex
so you can pass all Flex
props.
NumberDecrementStepper and NumberIncrementStepper Props#
NumberDecrementStepper
and NumberIncrementStepper
composes the Box
props
so you can pass all Box
props.
The NumberInput
component is a multipart component. The styling needs to be
applied to each part specifically.
To learn more about styling multipart components, visit the Component Style page.
Anatomy#
- A:
root
- B:
field
- C:
stepperGroup
- D:
stepper
Theming properties#
The properties that affect the theming of the NumberInput
component are:
variant
: The visual variant of the button. Defaults tooutline
.size
: The size of the button. Defaults tomd
.
Theming utilities#
createMultiStyleConfigHelpers
: a function that returns a set of utilities for creating style configs for a multipart component (definePartsStyle
anddefineMultiStyleConfig
).definePartsStyle
: a function used to create multipart style objects.defineMultiStyleConfig
: a function used to define the style configuration for a multipart component.
import { numberInputAnatomy } from '@chakra-ui/anatomy'import { createMultiStyleConfigHelpers } from '@chakra-ui/react'const { definePartsStyle, defineMultiStyleConfig } =createMultiStyleConfigHelpers(numberInputAnatomy.keys)
Customizing the default theme#
import { numberInputAnatomy } from '@chakra-ui/anatomy'import { createMultiStyleConfigHelpers } from '@chakra-ui/react'const { definePartsStyle, defineMultiStyleConfig } =createMultiStyleConfigHelpers(numberInputAnatomy.keys)const baseStyle = definePartsStyle({// define the part you're going to stylefield: {fontWeight: 'semibold',color: 'red.500',},})export const numberInputTheme = defineMultiStyleConfig({ baseStyle })
After customizing the number input theme, we can import it in our theme file and
add it in the components
property:
import { extendTheme } from '@chakra-ui/react'import { numberInputTheme } from './components/number-input'export const theme = extendTheme({components: { NumberInput: numberInputTheme },})
This is a crucial step to make sure that any changes that we make to the input theme are applied.
Adding a custom size#
Let's assume we want to include an extra large input size. Here's how we can do that:
import { numberInputAnatomy } from "@chakra-ui/anatomy";import { createMultiStyleConfigHelpers, defineStyle } from "@chakra-ui/react";const {definePartsStyle,defineMultiStyleConfig} = createMultiStyleConfigHelpers(numberInputAnatomy.keys);const xl = defineStyle({fontSize: "lg",h: "20",px: "2"});const sizes = {xl: definePartsStyle({ field: xl, stepper: xl, addon: xl })};export const numberInputTheme = defineMultiStyleConfig({ sizes });// Now we can use the new `xl` size<NumberInput size="xl" ... />
Every time you're adding anything new to the theme, you'd need to run the CLI command to get proper autocomplete in your IDE. You can learn more about the CLI tool here.
Adding a custom variant#
Let's assume we want to include a custom primary variant. Here's how we can do that:
import { numberInputAnatomy } from "@chakra-ui/anatomy";import { createMultiStyleConfigHelpers } from "@chakra-ui/react";const {definePartsStyle,defineMultiStyleConfig} = createMultiStyleConfigHelpers(numberInputAnatomy.keys);const primary = definePartsStyle({field: {border: "1px solid",borderColor: "gray.200",background: "gray.50",fontWeight: "bold",// Let's also provide dark mode alternatives_dark: {borderColor: "gray.600",background: "gray.800"}},stepper: {color: "purple.500",background: "gray.200"}});export const numberInputTheme = defineMultiStyleConfig({variants: { primary }});// Now we can use the new `pill` variant<NumberInput variant="primary" ... />
Changing the default properties#
Let's assume we want to change the default size and variant of every number input in our app. Here's how we can do that:
import { numberInputAnatomy } from '@chakra-ui/anatomy'import { createMultiStyleConfigHelpers, defineStyle } from '@chakra-ui/react'const { defineMultiStyleConfig } = createMultiStyleConfigHelpers(numberInputAnatomy.keys,)export const numberInputTheme = defineMultiStyleConfig({defaultProps: {size: 'xl',variant: 'primary',},})// This saves you time, instead of manually setting the size and variant every time you use an input:<NumberInput size="xl" variant="primary" ... />
Showcase#
import { Box, IconButton, NumberDecrementStepper, NumberIncrementStepper, NumberInput, NumberInputField, NumberInputStepper, SimpleGrid, useColorMode, Text } from "@chakra-ui/react"; import { FaMoon, FaSun } from "react-icons/fa"; export default function App() { const { toggleColorMode, colorMode } = useColorMode(); return ( <Box position="relative" h="100vh"> <SimpleGrid gap={12} p={12} columns={2}> <Box> <Text fontSize="sm">Themed filled number input:</Text> <NumberInput variant="filled"> <NumberInputField /> <NumberInputStepper> <NumberIncrementStepper /> <NumberDecrementStepper /> </NumberInputStepper> </NumberInput> </Box> <Box> <Text fontSize="sm">Themed outline number input:</Text> <NumberInput variant="outline"> <NumberInputField /> <NumberInputStepper> <NumberIncrementStepper /> <NumberDecrementStepper /> </NumberInputStepper> </NumberInput> </Box> <Box> <Text fontSize="sm">Themed flushed number input:</Text> <NumberInput variant="flushed"> <NumberInputField /> <NumberInputStepper> <NumberIncrementStepper /> <NumberDecrementStepper /> </NumberInputStepper> </NumberInput> </Box> <Box> <Text fontSize="sm">Custom variant number input:</Text> <NumberInput variant="primary"> <NumberInputField /> <NumberInputStepper> <NumberIncrementStepper /> <NumberDecrementStepper /> </NumberInputStepper> </NumberInput> </Box> </SimpleGrid> <IconButton aria-label="toggle theme" rounded="full" size="xs" position="absolute" bottom={4} left={4} onClick={toggleColorMode} icon={colorMode === "dark" ? <FaSun /> : <FaMoon />} /> </Box> ); }