npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@bitovi/react-numerics

v1.3.4

Published

A library of React components to render input fields that simplify displaying formatted numbers such as currency or telephone numbers.

Downloads

766

Readme

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.

👉 If 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.
  • report if true the input's reportValidity 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.