react-number-format

repository·master·Indexed 26 days ago

https://github.com/s-yadav/react-number-format

A lightweight input-formatter library for React that allows formatting numbers in inputs or as text. It features components like NumericFormat for numeric input formatting and PatternFormat for input masking (e.g., phone numbers or dates). The library provides a sophisticated caret engine, support for custom prefixes, suffixes, thousands separators, and custom validation via the isAllowed prop.

Tokens
11.8K
Snippets
43
Records
85
Agent score
83%

What's inside react-number-format

  1. Overview of react-number-format features

    master

    React Number Format is a lightweight input-formatter library with a caret engine that ensures user input meets specific numeric or string patterns. Key features include:

    • Prefix, suffix, and thousands separator support.
    • Input Masking.
    • Formatting numbers in inputs or as simple text.
    • Custom pattern formatting.
    • Custom formatting handlers.
    • Full customizability.
  2. Extend NumericFormat using useNumericFormat hook

    master

    To add custom behavior (like non-standard numerals or custom removal logic) on top of NumericFormat, use the useNumericFormat hook. This hook provides format, removeFormatting, and isCharacterSame functions that you can wrap with your own logic and pass to NumberFormatBase.

    const persianNumeral = ['۰', '۱', '۲', '৩', '۴', '৫', '৬', '৭', '৮', '৯'];
    
    function CustomNumeralNumericFormat(props) {
      const { format, removeFormatting, isCharacterSame, ...rest } = useNumericFormat(props);
    
      const _format = (val) => {
        const _val = format(val);
    
        return _val.replace(/\d/g, ($1) => persianNumeral[Number($1)]);
      };
    
      const _removeFormatting = (val) => {
        const _val = val.replace(new RegExp(persianNumeral.join('|'), 'g'), ($1) =>
          persianNumeral.indexOf($1),
        );
    
        return removeFormatting(_val);
      };
    
      const _isCharacterSame = (compareMeta) => {
        const isCharSame = isCharacterSame(compareMeta);
        const { formattedValue, currentValue, formattedValueIndex, currentValueIndex } = compareMeta;
        const curChar = currentValue[currentValueIndex];
        const newChar = formattedValue[formattedValueIndex];
        const curPersianChar = persianNumeral[Number(curChar)] ?? curChar;
        const newPersianChar = persianNumeral[Number(newChar)] ?? newChar;
    
        return isCharSame || curPersianChar === newPersianChar;
      };
    
      return (
        <NumberFormatBase
          format={_format}
          removeFormatting={_removeFormatting}
          isCharacterSame={_isCharacterSame}
          {...rest}
        />
      );
    }
  3. Configure input behavior and constraints

    master

    Follow these guidelines for common input configurations:

    • Numeric Strings: If you pass a string as the value prop and your prefix/suffix contains numbers, set valueIsNumericString={true}.
    • Decimal Control: To prevent floating-point numbers, set decimalScale={0}.
    • Mobile Keyboards: Use type="tel" when providing a format prop to trigger a numeric keypad on mobile devices. Otherwise, use type="text" to allow users to type decimal separators.
    • Length Constraints: Native minLength and maxLength props do not work reliably because formatting occurs after the number is added. Use the isAllowed prop to implement custom length constraints.
  4. Deploy the documentation website

    master

    You can deploy the website using different methods depending on your hosting configuration.

    Using SSH:

    $ USE_SSH=true yarn deploy

    Using GitHub (Non-SSH): If you are using GitHub Pages, provide your GitHub username to build the site and push it to the gh-pages branch.

    $ GIT_USER=<Your GitHub username> yarn deploy
    $ USE_SSH=true yarn deploy
    # OR
    $ GIT_USER=<Your GitHub username> yarn deploy
  5. Import NumberFormat

    master

    Depending on your environment, import the component as follows:

    ES6 / TypeScript

    import NumberFormat from 'react-number-format';
    // or
    import { default as NumberFormat } from 'react-number-format';

    ES5

    const NumberFormat = require('react-number-format');

    Note for TypeScript users: You must enable "esModuleInterop": true in your tsconfig.json.

    import NumberFormat from 'react-number-format';
  6. Extend PatternFormat using usePatternFormat hook

    master

    To combine the features of PatternFormat (like pattern matching) with custom logic, use the usePatternFormat hook. The hook returns all the props required for NumberFormatBase, which you can then extend or override.

    function CardExpiry(props) {
      /**
       * usePatternFormat, returns all the props required for NumberFormatBase
       * which we can extend in between
       */
      const { format, ...rest } = usePatternFormat({ ...props, format: '##/##' });
    
      const _format = (val) => {
        let month = val.substring(0, 2);
        const year = val.substring(2, 4);
    
        if (month.length === 1 && month[0] > 1) {
          month = `0${month[0]}`;
        } else if (month.length === 2) {
          // set the lower and upper boundary
          if (Number(month) === 0) {
            month = `01`;
          } else if (Number(month) > 12) {
            month = '12';
          }
        }
    
        return format(`${month}${year}`);
      };
    
      return <NumberFormatBase format={_format} {...rest} />;
    }
  7. Migrate from NumberFormat to NumericFormat or PatternFormat

    master

    In v5, the monolithic NumberFormat component has been split into specialized components.

    • Use NumericFormat for number-based formatting (e.g., currency inputs).
    • Use PatternFormat for pattern-based formatting (e.g., credit card numbers, phone numbers).

    Update your imports accordingly.

    // Old way (v4)
    import NumberFormat from 'react-number-format';
    
    // New way (v5)
    import { NumericFormat } from 'react-number-format';
    // or
    import { PatternFormat } from 'react-number-format';