MUINumberInput
MUINumberInput is a
TextField-based numeric input
that enforces number-only entry with options for integers-only, non-negative
values, a maximum number of decimal places, min / max bounds, and keyboard
step increments.
For always-visible - / + buttons instead of the native browser steppers,
use MUINumberStepper.
Usage
import MUINumberInput, { MUINumberInputProps } from '@nish1896/mui-components/mui/number-input';const [age, setAge] = useState<number | null>(null);
<MUINumberInput
fieldName="age"
value={age}
onValueChange={({ newValue, event }) => setAge(newValue)}
onlyIntegers
nonNegative
/>onValueChange receives { newValue, event }: the parsed number, or null
when the field is empty, and the change event.
Validation
MUINumberInput rejects invalid keystrokes and pasted text up front, instead of
correcting them afterwards. Combine the props below to describe the numbers you
accept. The characters e, E and + are always blocked, and so is a second
minus sign.
Integers only
onlyIntegers blocks the decimal point. A pasted decimal is cut to its whole
part, so 43.234 becomes 43. Stepping also moves by whole numbers:
stepAmount is rounded down, with a minimum of 1.
<MUINumberInput
fieldName="quantity"
value={quantity}
onValueChange={({ newValue }) => setQuantity(newValue)}
onlyIntegers
/>Non-negative values
nonNegative blocks the minus sign, typed or pasted, so a pasted -43.5
becomes 43.5. It also acts as an implicit min of 0.
<MUINumberInput
fieldName="price"
value={price}
onValueChange={({ newValue }) => setPrice(newValue)}
nonNegative
/>Decimal places
maxDecimalPlaces limits the digits after the decimal point. The user can't
type more, and a pasted 3.14159 becomes 3.14 when the limit is 2. Don't
combine it with onlyIntegers.
<MUINumberInput
fieldName="weight"
value={weight}
onValueChange={({ newValue }) => setWeight(newValue)}
nonNegative
maxDecimalPlaces={2}
/>Minimum and maximum
The min and max props, added in v2.2 set the upper and lower bounds.
Stepping with the arrow keys or the markers stops at them. Typing and pasting
are not blocked while the user is editing, so the field can briefly hold
an out-of-range number, such as 7 on the way to 70. When the field loses
focus, an out-of-range value is clamped to the nearest bound and onValueChange
is called with the clamped number.
nonNegative sets the lower bound to 0, and an explicit min overrides it.
A min greater than max throws an error.
<MUINumberInput
fieldName="age"
value={age}
onValueChange={({ newValue }) => setAge(newValue)}
onlyIntegers
min={18}
max={65}
/>Showing validation messages
Because the bounds are applied on blur, show a message while the user is still
typing by checking the new value yourself and passing the result to
errorMessage. The error clears as soon as the value is back in range,
including when the blur clamps it:
const [age, setAge] = useState<number | null>(null);
const [ageError, setAgeError] = useState<string>();
<MUINumberInput
fieldName="age"
value={age}
onValueChange={({ newValue }) => {
setAge(newValue);
setAgeError(
newValue !== null && (newValue < 18 || newValue > 65)
? 'Enter an age between 18 and 65'
: undefined
);
}}
errorMessage={ageError}
helperText="Between 18 and 65"
onlyIntegers
min={18}
max={65}
/>Formatting the displayed value
The renderValue prop, added in v2.2 formats the number for display -
thousands separators, a currency prefix, fixed decimals. The field switches to
type="text" (which can render grouping characters) and shows the formatted
string only while it is not focused; on focus it reverts to the raw number
and every typing / paste / min / max rule still applies. value stays a
real number | null.
const [salary, setSalary] = useState<number | null>(null);
<MUINumberInput
fieldName="salary"
value={salary}
onValueChange={({ newValue }) => setSalary(newValue)}
nonNegative
maxDecimalPlaces={2}
renderValue={val => val === null
? ''
: val.toLocaleString('en-IN', {
style: 'currency',
currency: 'INR'
})
}
/>API
MUINumberInputProps accepts most
TextFieldProps, with some props
excluded, including type, multiline and rows.
Props marked with * are required.
| Name | Type | Description |
|---|---|---|
fieldName* | string | Name/path of the field. Used to derive the id, the default label, and the name attribute. This prop is required for all components. |
value | number | null | Current numeric value of the field. undefined/null render an empty input. |
onValueChange* | ({ newValue, event }) => void | Called on every accepted numeric change. newValue is null when the input is cleared. |
min | number | Lower bound for the value. Stepping (arrow keys / markers) clamps to this and the value is clamped on blur. nonNegative sets the lower bound to 0, but min overrides it when set.Added in v2.2. |
max | number | Upper bound for the value. Stepping (arrow keys / markers) clamps to this and the value is clamped on blur. Added in v2.2. |
onlyIntegers | boolean | When true, decimal input is not allowed. Cannot be combined with maxDecimalPlaces. |
nonNegative | boolean | When true, negative values cannot be entered. |
maxDecimalPlaces | number | Maximum number of decimal places accepted while typing. |
stepAmount | number | Amount the value changes on Arrow Up/Down key presses. |
showMarkers | boolean | When true, shows increment/decrement markers on the input. |
renderValue | (value: number | null) => string | Formats the numeric value for display, e.g. value => value?.toLocaleString() ?? '' for thousands separators. Switches the input to type="text" (which can render grouping characters); the formatted string is shown only while the field is not focused — on focus it reverts to the raw number and every typing / paste / min / max rule still applies. value stays a real number | null.Added in v2.2. |
label | ReactNode | Label displayed for the field. Defaults to a human-readable label derived from fieldName, e.g. firstName becomes "First Name". |
showLabelAboveFormField | boolean | When true, renders the field label above the form field in the FormLabel component, instead of inside or beside it. Takes precedence over allLabelsAboveFields from the ConfigProvider, so false keeps the label inside this field even when the config places every label above its field. |
formLabelProps | FormLabelProps | FormLabelProps forwarded to the internal FormLabel. The id is managed by the component. Multiple fields can be configured using the ConfigProvider component. |
hideLabel | boolean | When true, hides the rendered field label while preserving accessible labeling where possible. |
required | boolean | Indicates that the field is mandatory by adding an asterisk symbol (*) to the form label and setting the relevant accessibility attributes. |
errorMessage | string | string[] | Validation error for the field — pass a single message string, or a string[] when the field can fail multiple rules at once (every message is shown together). A non-empty string or array puts the field in an error state; undefined/''/[] clear it.Normalize your form library's error shape to this at the call site (e.g. an RHF FieldError via its .message). Use renderError to customize how the message(s) are rendered. |
renderError | (errors: string[]) => ReactNode | Custom renderer for the resolved error message(s), called only when the field is in an error state. Always receives a string[] — use errors[0] for the common single-message case, or map over errors when a field fails several rules. By default a single message renders as text and multiple messages render on separate lines. |
hideErrorMessage | boolean | If true, hides the error message text while keeping the field in an error state. |
formHelperTextProps | FormHelperTextProps | FormHelperTextProps forwarded to the internal FormHelperText. The id is managed by the component. Multiple fields can be configured using the ConfigProvider component. |
customIds | { field, label, helperText, error } | Overrides the default field, label, helper text, and error IDs used for accessibility. |
Playground
Integrated with TanStack Form — covers
onlyIntegers, nonNegative, maxDecimalPlaces, stepAmount, showMarkers,
showLabelAboveFormField and renderValue with validation surfaced through
errorMessage.
Reference
Source Code
View the full implementation of this component on GitHub.