react-numerics
A library of React components to render input fields that simplify displaying formatted numbers such as currency or telephone numbers.
Need help or have questions?
This project is supported by Bitovi, an end-to-end JavaScript consultancy specializing in React. You can get help or ask questions on our:
Or, you can hire us for training, consulting, or development. Set up a free consultation.
Install
Install the package.
npm install @bitovi/react-numerics
-or-
yarn add @bitovi/react-numerics
Usage
Available components
The following types of components are currently available:
Use | Component | Locales | Note |
---|---|---|---|
currency | CurrencyNumberInput | any | |
percent | PercentNumberInput | any | |
phone number | TelephoneNumberInput | en-US | 10 digit - area code and exchange required |
postal code | PostalCodeNumberInput | en-US | 5 digit |
social security number | SocialSecurityNumberInput | US only | |
employer identification number | EmployerIdentificationNumberInput | US only |
Import the component that you need.
import { PercentNumberInput } from "@bitovi/react-numerics";
export function Form({ numericValue }: Props) {
function handleNumericChange(value) {
// Do something with the value.
}
return (
<PercentNumberInput
numericValue={numericValue}
onNumericChange={handleNumericChange}
validate
/>
);
}
Components require the numericValue
and onNumericChange
props. Each
component accepts values for most of the standard HTMLInputElement
attributes
with the notable exception of type
.
Each component will render an unstyled <input>
element with type
equal to
"text".
Reference to the input element
Each component implements React's forwardRef
interface that will return a
reference to the underlying <input>
element.
import { PostalCodeNumberInput } from "@bitovi/react-numerics";
export function Form({ numericValue }: Props) {
const myRef = React.useRef<HTMLInputElement | null>(null);
// Once rendered, `myRef.current` is the underlying <input> element.
function handleNumericChange(value) {
// Do something with the value.
}
return (
<PostalCodeNumberInput
numericValue="01970"
onNumericChange={handleNumericChange}
ref={myRef}
validate
/>
);
}
Validation
As of version 1.3.4 validation is built-in to the current higher order components as well as being available through interfaces and functionality for composing new components.
By default validation is NOT enabled in components so that it doesn't
interfere with any custom validation that may have been created using a
component's ref
.
To enable validation add the validate
prop to a component. When the component
fails validation the :invalid
pseudo class will be set on the input element.
The browser's default error UI will be displayed with an English error message;
this behavior can be changed.
Currently validation is performed when:
- a component first mounts
- the value of an input changes
- a component loses focus (i.e. blur)
Modifying the validation result
There are two ways to modify the text of the message that is displayed to the
user, the simplest is to provide a string using the input element's title
attribute. If the input is invalid the title is displayed. The same message is
always displayed regardless of the reason the input is invalid.
The most flexible way to alter how a component is validated — and the
error text — is by adding the updateCustomValidity
prop with a callback
function. This callback is invoked with three arguments: a number
which is the
current numeric value, context
which has information about the conditions the
validator is being invoked under, and result
that contains the validation
result generated by the default validation.
updateCustomValidity
is provided you do not need to set
validate=true
; that will be inferred.
The value of result.customValidity
will be a string constant from
ValidateErrorTypes
that indicates the type of validation error.
The callback can either return void
or a ValidationResult
with the
validation that should be applied. If void is returned the current validity of
the input will not be changed. When returning a ValidationResult
:
-
customValidity
- An empty string
""
will make the input valid. - Any string will be set as the input's validation message and may be displayed to the user.
- An empty string
-
report
if true the input'sreportValidity
method will be invoked and will cause the browser to display the value of customValidity, if false the validity will be updated but the user will not be informed of the current validity status.
The following example illustrates code that sets a localized string for the error message that will be displayed to the user.
import { PostalCodeNumberInput } from "@bitovi/react-numerics";
export function Form({ handleNumericChange, getLocalizedString, numericValue }: Props) {
function updateCustomValidity(number, context, result) {
if(result.customValidity){
// Create a new ValidationResult where the customValidity
// property is set to a localized string. So for example
// the constant "INVALID_LESS_THAN_MIN_LENGTH" might
// result in a string like
// "El valor del código postal debe tener 5 dígitos."
return {
...result,
customValidity: getLocalizedString(result.customValidity, { minimum: context.minLength })
};
}
return result;
}
return (
<PostalCodeNumberInput
numericValue={numericValue}
onNumericChange={handleNumericChange}
updateCustomValidity={updateCustomValidity}
/>
);
}
We want to hear from you
Come chat with us about open source in our community Discord.
See what we're up to by following us on Twitter.