MUI Components
NPM

MUIUnitInput

MUIUnitInput pairs a numeric value (MUINumberInput) with a unit picker (MUISelect) - currency, weight, temperature, or any other unit set - rendered borderless inside one bordered pill, similar in spirit to MUIPhoneInput's country + number pairing.

fieldName and customIds are both { unit, value } objects — one entry per control, so each is registered independently against a flat form schema. fieldName requires both keys; customIds keys are optional. value / onValueChange still report the pair together as one { unit, value } object. containerProps styles the outer pill container; dividerProps styles the vertical divider between the two controls.

unitOptions accepts either a plain string array, or an object array read via labelKey/valueKey — the same convention as MUISelect.

Always seed value.unit with a real option — an empty/missing unit renders the unit Select with nothing selected rather than silently defaulting to unitOptions[0], so what's shown always matches what you passed in.

Usage

import MUIUnitInput, { MUIUnitInputValue } from '@nish1896/mui-components/mui/unit-input';

Plain string unitOptions:

const [price, setPrice] = useState<MUIUnitInputValue>({
  unit: 'USD',
  value: null
});

<MUIUnitInput
  fieldName={{
    unit: 'priceUnit',
    value: 'priceAmount'
  }}
  value={price}
  onValueChange={({ newValue, event }) => setPrice(newValue)}
  unitOptions={['USD', 'EUR', 'GBP']}
  nonNegative
  maxDecimalPlaces={2}
/>

onValueChange receives { newValue, event }: newValue is the whole { unit, value } object, and event is the event of the part that changed, either the number input or the unit select.

With an array of objects

Pass an array of objects as unitOptions, with labelKey and valueKey naming two of their properties. labelKey is the text shown in the unit picker, and valueKey is the value stored in value.unit. The type of newValue.unit comes from the valueKey property.

In the above example below, the type of price.currency will be 'USD' | 'EUR' | 'GBP', so the type of price will be MUIUnitInputValue<Currency>.

type Currency = 'USD' | 'EUR' | 'GBP';
type CurrencyOption = { code: Currency; label: string };

const currencyOptions: CurrencyOption[] = [
  { code: 'USD', label: 'US Dollar' },
  { code: 'EUR', label: 'Euro' },
  { code: 'GBP', label: 'British Pound' }
];

const [price, setPrice] = useState<MUIUnitInputValue<Currency>>({
  unit: 'USD',
  value: null
});

<MUIUnitInput
  fieldName={{
    unit: 'priceUnit',
    value: 'priceAmount'
  }}
  value={price}
  onValueChange={({ newValue }) => setPrice(newValue)}
  unitOptions={currencyOptions}
  labelKey="label"
  valueKey="code"
  unitPosition="start"
/>
Warning

When unitOptions is an array of objects, an error is thrown if either labelKey or valueKey is missing. An error is also thrown when unitOptions is not an array.

Value input options

The value input is a MUINumberInput, so its usual number props are available directly on MUIUnitInput, and they apply to the numeric value only:

  • min and max: the lower and upper bounds. Stepping stops at them, and an out-of-range value is clamped when the input loses focus.
  • nonNegative: blocks the minus sign and acts as an implicit min of 0, unless you set min.
  • onlyIntegers: allows whole numbers only. Don't combine it with maxDecimalPlaces.
  • maxDecimalPlaces: limits how many digits can follow the decimal point.
  • stepAmount: how much the arrow keys change the value by. Defaults to 1.
  • renderValue: formats the number for display, such as a currency or thousands separators. The raw number is shown while the input is focused, and value.value stays a real number | null.
  • placeholder: text shown while the value input is empty.
<MUIUnitInput
  fieldName={{
    unit: 'weightUnit',
    value: 'weight'
  }}
  value={weight}
  onValueChange={({ newValue }) => setWeight(newValue)}
  unitOptions={['kg', 'lb']}
  nonNegative
  min={1}
  max={500}
  maxDecimalPlaces={1}
  stepAmount={0.5}
  placeholder="Enter weight"
/>

Customizing the value input

valueInputProps is forwarded to the internal MUINumberInput, for example an sx, an onBlur handler or an inputRef. The component controls a few props itself, so they can't be set here: the field name, value and onValueChange, variant, showMarkers, the label, error and helper text props, customIds, required, disabled, placeholder, and the number props listed above. Set the last group directly on MUIUnitInput instead.

<MUIUnitInput
  fieldName={{
    unit: 'weightUnit',
    value: 'weight'
  }}
  value={weight}
  onValueChange={({ newValue }) => setWeight(newValue)}
  unitOptions={['kg', 'lb']}
  valueInputProps={{
    sx: { '& input': { fontWeight: 700 } },
    onBlur: () => setWeightTouched(true)
  }}
/>

Customizing the unit select

unitSelectProps is forwarded to the internal MUISelect that picks the unit. That makes renderOptionLabel, getOptionDisabled, renderValue and menuItemProps available for the unit options. Its sx is merged with the select's base styles. The component controls the field name, options, labelKey, valueKey, value and onValueChange, variant, multiple, the label, error and helper text props, customIds, required and disabled.

<MUIUnitInput
  fieldName={{
    unit: 'priceUnit',
    value: 'priceAmount'
  }}
  value={price}
  onValueChange={({ newValue }) => setPrice(newValue)}
  unitOptions={currencyOptions}
  labelKey="label"
  valueKey="code"
  unitSelectProps={{
    renderOptionLabel: option => `${option.label} (${option.code})`,
    getOptionDisabled: option => option.code === 'GBP',
    sx: { fontWeight: 600 }
  }}
/>

Unit position and width

unitPosition sets which side of the value input the unit select renders on: 'end' (the default) or 'start'. The divider between the two controls moves with it. Use 'start' for formats where the unit comes first, such as a currency.

unitWidth sets the width of the unit select as a CSS flex-basis, and the value input fills the rest of the pill. Pass a percentage of the pill such as '30%', a fixed width such as '100px', or a responsive object such as { xs: '40%', md: '30%' }. Once it is set, the unit select keeps that width instead of shrinking. When unitWidth is omitted, the unit select is sized to its selected option. Either way, both controls keep a minimum width of 50px, so neither collapses.

<MUIUnitInput
  fieldName={{
    unit: 'priceUnit',
    value: 'priceAmount'
  }}
  value={price}
  onValueChange={({ newValue }) => setPrice(newValue)}
  unitOptions={['USD', 'EUR', 'GBP']}
  unitPosition="start"
  unitWidth="35%"
/>

A responsive width gives the unit select more room on small screens:

<MUIUnitInput
  fieldName={{
    unit: 'weightUnit',
    value: 'weight'
  }}
  value={weight}
  onValueChange={({ newValue }) => setWeight(newValue)}
  unitOptions={['kg', 'lb']}
  unitWidth={{ xs: '40%', md: '30%' }}
/>

API

Props marked with * are required.

NameTypeDescription
fieldName*{ unit: string; value: string; }
Name/path of the field's two underlying controls, kept separate (rather than one combined fieldName) so each can be registered independently against a flat form schema — e.g. { unit: 'weightUnit', value: 'weight' }.
unitOptions*Option[]
Units selectable from the dropdown — a plain string array (e.g. ['USD', 'EUR', 'GBP'] or ['kg', 'lb'], a string-literal union/enum's values for literal-union safety), or an object array read via labelKey/valueKey, same convention as MUISelect.
labelKeystring
Object key used to read the display label from each option, when unitOptions is an array of objects.
valueKeystring
Object key used to derive the unit value from each option, when unitOptions is an array of objects.
value{ unit: string; value: number | null; }
Current value of the field. unit and value are always reported together through onValueChange, even though they are two controls.
onValueChange*({ newValue, event }) => void
Called whenever either the unit or the value changes. Always receives the full { unit, value } value.
minnumber
Lower bound for the value. nonNegative sets the default value to 0 unless overridden.
maxnumber
Upper bound for the value.
onlyIntegersboolean
When true, decimal input is not allowed. Cannot be combined with maxDecimalPlaces.
nonNegativeboolean
When true, negative values cannot be entered.
maxDecimalPlacesnumber
Maximum number of decimal places accepted while typing.
stepAmountnumber
Amount the value changes on Arrow Up/Down key presses.
renderValue(value: number | null) => string
Formats the numeric value for display, e.g. value => value?.toLocaleString() ?? '' for thousands separators or a currency prefix. Forwarded to the internal MUINumberInput: the raw number is shown while the value input is focused, the formatted string when it is not, and value.value stays a real number | null.
unitPosition'start' | 'end'
Which side the unit Select renders on relative to the value input.
Default: 'end'
unitWidthResponsiveStyleValue<string>
Width of the unit Select as a CSS flex-basis value, the value input fills the rest. Accepts a single value (e.g. 100px or '30%') or a responsive breakpoint object, e.g. { xs: '40%', md: '30%' }.
Both segments have a default minWidth: 50px so neither collapses. When omitted, the unit Select sizes to its content.
unitSelectPropsMUISelectProps
Props forwarded to the internal unit MUISelect.
valueInputPropsMUINumberInputProps
Props forwarded to the internal MUINumberInput determining the value of the field.
containerPropsBoxProps
Props forwarded to the outer pill container wrapping the value input and unit Select. containerProps.sx is merged with the component's own base pill styles rather than replacing them, and accepts any sx form — object, array, or function.
dividerPropsBoxProps
Props forwarded to the vertical divider between the value input and the unit Select (a plain Box with borderLeft/borderColor).
labelReactNode
Custom field label. Defaults to a humanized version of fieldName.value.
showLabelAboveFormFieldboolean
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.
formLabelPropsFormLabelProps
FormLabelProps forwarded to the internal FormLabel. The id is managed by the component. Multiple fields can be configured using the ConfigProvider component.
hideLabelboolean
When true, hides the rendered field label while preserving accessible labeling where possible.
requiredboolean
Indicates that the field is mandatory by adding an asterisk symbol (*) to the form label and setting the relevant accessibility attributes.
placeholderstring
Placeholder shown in the empty value input.
disabledboolean
When true, disables the field and associated controls.
errorMessagestring | 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.
hideErrorMessageboolean
If true, hides the error message text while keeping the field in an error state.
helperTextReactNode
Content displayed in the FormHelperText component below the field when there is no visible validation error.
formHelperTextPropsFormHelperTextProps
FormHelperTextProps forwarded to the internal FormHelperText. The id is managed by the component. Multiple fields can be configured using the ConfigProvider component.
customIds{ unit?: CustomComponentIds; value?: CustomComponentIds }
Custom ids for the unit and value controls respectively.

Playground

Driven by plain React state — three fields, all required and validated on submit:

  • Currency — object unitOptions via labelKey/valueKey, unit on the left (unitPosition="start"), with renderOptionLabel and getOptionDisabled forwarded through unitSelectProps; nonNegative with maxDecimalPlaces={2}, and renderValue.
  • Weight — plain string unitOptions, responsive unitWidth ({ xs: '40%', md: '30%' }), onlyIntegers and max={150}.
  • Temperature — containerProps / dividerProps and sx overrides on the internal quantity input and unit Select.

Currency, object unitOptions via labelKey/valueKey, unit on the left, renderOption/getOptionDisabled, and renderValue reformatting per selected currency

Blur to see it formatted as the selected currency

Weight, plain string unitOptions, responsive unitWidth (40% on mobile, 30% from md up)

Only Integers, stepAmount: 5, max limit: 150

Temperature — containerProps, dividerProps, and sx overrides on the internal quantity input & unit Select

Form State - Values & Errors

Unit-Input integration with react-hook-form and zod validation.

Distance, object unitOptions via labelKey/valueKey, unit on the left, getOptionDisabled, and renderValue reformatting per selected unit

Blur to see it reformatted with the selected unit

File size, nested storage.unit/storage.amount field paths, plain string unitOptions, responsive unitWidth (40% on mobile, 30% from md up), containerProps, dividerProps, and sx overrides

Only integers, stepAmount: 10, containerProps, dividerProps, valueInputProps.sx, unitSelectProps.sx all overridden here

Form State - Values & Errors

Source Code

View the full implementation of this component on GitHub.