1.0.5 • Published 2 years ago

react-amount v1.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

React component formatting numbers in an input field

GitHub open issues MIT Coverage Status

Live demo

Live demo on CodeSandbox

npm.io

Installation

yarn add react-amount

or

npm install react-amount

Usage

import React, { useState } from 'react';
import { Amount } from 'react-amount';

import '~/react-amount/dist/style/index.min.css';

interface MyComponentProps {
  value: string | number | undefined;
}

const MyComponent = (props: MyComponentProps): React.Element => {
  const { value } = props;

  const [currentValue, setCurrentValue] = useState<string | number | undefined>(
    value,
  );

  return (
    <Amount
      value={currentValue}
      suffix="€"
      onChange={(newValue) => setCurrentValue(newValue.raw)}
      decimalSeparator=","
      thousandSeparator=" "
    />
  );
};

export default MyComponent;

Options

OptionTypeDefault valueDescription
valuestring | numberundefinedInitial value of the control
readOnlybooleanfalseInput value is not editable
disabledbooleanfalseInput value is disabled
textOnlybooleanfalseInput value is displayed as formatted text only value
namestringName of the input field
classNamestringundefinedClass to be added to the wrapper of the component
onChange(update: FormattedValues) => voidundefinedCallback function to handle value changes
decimalsnumber2Number of decimals
decimalSeparatorstring"."Decimal separator
thousandSeparatorstring","Thousand separator
thousandGroupingThousandGroupingStyle: "thousand" | "wan" | "lakh""thousand"Thousand grouping style
displayOnInvalidstring"-"Value displayed on invalid input in textOnly
dataTestIdstringundefinedId value for testing
requiredbooleanfalseRequired of the input field
prefixstringundefinedPrefix
suffixstringundefinedSuffix

Contributing

We very much welcome contributions.

Types

FormattedValues

export interface FormattedValues {
  formatted: string;
  float: number;
  raw: string;
}

This structure is used in the onChange handler to provide flexibility on the format.

  • formatted is for display purpose.
  • float is for numerical representation, but suffer from precision limitations.
  • raw is for numerical representation as a string with full precision.

ThousandGroupingStyle

export enum ThousandGroupingStyle {
  THOUSAND = 'thousand',
  WAN = 'wan',
  LAKH = 'lakh',
}
  • THOUSAND: groups of 3 digits example: 123,456,789
  • WAN: 1 group of 4 digits, then groups of 3 digits example: 12,345,6789
  • LAKH: 1 group of 3 digits, then groups of 2 digits example: 12,34,56,789