16.11.0 • Published 5 months ago

@commercetools-uikit/money-input v16.11.0

Weekly downloads
5,130
License
MIT
Repository
github
Last release
5 months ago

MoneyInput

Description

A controlled input component for money values with validation states.

Installation

yarn add @commercetools-uikit/money-input
npm --save install @commercetools-uikit/money-input

Additionally install the peer dependencies (if not present)

yarn add react react-dom react-intl
npm --save install react react-dom react-intl

Usage

import MoneyInput from '@commercetools-uikit/money-input';

const Example = () => (
  <MoneyInput
    value={{ amount: '1.00', currencyCode: 'EUR' }}
    onChange={
      (/** event */) => {
        // alert(event.target.name, event.target.value)
      }
    }
    currencies={['EUR', 'USD']}
  />
);

export default Example;

Properties

PropsTypeRequiredDefaultDescription
idstringUsed as HTML id property. An id is auto-generated when it is not specified.
autoCompletestringUsed as HTML autocomplete property
aria-invalidbooleanIndicate if the value entered in the input is invalid.
aria-errormessagestringHTML ID of an element containing an error message related to the input.
namestringThe prefix used to create a HTML name property for the amount input field (${name}.amount) and the currency dropdown (${name}.currencyCode).
valueObjectSee signature.Value of the input. Consists of the currency code and an amount. amount is a string representing the amount. A dot has to be used as the decimal separator.
currenciesArray: string[][]List of possible currencies. When not provided or empty, the component renders a label with the value's currency instead of a dropdown.
placeholderstringPlaceholder text for the input
onBlurFunctionSee signature.Called when input is blurred
onFocusFunctionSee signature.Called when input is focused
isDisabledbooleanIndicates that the input cannot be modified (e.g not authorized, or changes currently saving).
isReadOnlybooleanIndicates that the field is displaying read-only content
isAutofocussedbooleanFocus the input on initial render
onChangeFunctionSee signature.Called with the event of the input or dropdown when either the currency or the amount have changed.
menuPortalTargetReactSelectProps['menuPortalTarget']Dom element to portal the currency select menu to Props from React select was used
menuPortalZIndexnumber1z-index value for the currency select menu portal Use in conjunction with menuPortalTarget
menuShouldBlockScrollReactSelectProps['menuShouldBlockScroll']whether the menu should block scroll while open Props from React select was used
hasErrorbooleanIndicates that input has errors
hasWarningbooleanControl to indicate on the input if there are selected values that are potentially invalid
hasHighPrecisionBadgebooleanShows high precision badge in case current value uses high precision.
horizontalConstraintunionPossible values:, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 'scale', 'auto''scale'Horizontal size limit of the input fields.

Signatures

Signature value

{
  amount: string;
  currencyCode: TCurrencyCode | '';
}

Signature onBlur

(event: TCustomEvent) => void

Signature onFocus

(event: TCustomEvent) => void

Signature onChange

(event: TCustomEvent) => void

Static methods

MoneyInput.convertToMoneyValue

The convertToMoneyValue function will turn a MoneyInput value into a MoneyValue the API can handle. It automatically converts to centPrecision or highPrecision types when the number of supplied fraction digits exceeds the number of fraction digits used by the currency. If you want to forbid highPrecision, then the form's validation needs to add an error when it sees a highPrecision price. See example below.

Here are examples of centPrecision and highPrecision prices.

// 42.00 €
{
  "type": "centPrecision",
  "currencyCode": "EUR",
  "centAmount": 4200,
  "fractionDigits": 2
}
// 0.0123456 €
{
 "type": "highPrecision",
 "currencyCode": "EUR",
 "centAmount": 1,
 "preciseAmount": 123456,
 "fractionDigits": 7
}

MoneyInput.parseMoneyValue

The parseMoneyValue function will turn a MoneyValue into a value the MoneyInput component can handle ({ amount, currencyCode }).

MoneyInput.isEmpty

The isEmpty function will return true when the passed MoneyInput value is empty (either has no currency or no amount, or does not exist at all).

MoneyInput.isEmpty({ amount: '', currencyCode: 'EUR' }); // -> true
MoneyInput.isEmpty({ amount: '5', currencyCode: '' }); // -> true
MoneyInput.isEmpty(); // -> true

MoneyInput.isEmpty({ amount: '5', currencyCode: 'EUR' }); // -> false

MoneyInput.isTouched

The isTouched function will return true when all input elements were touched (currency dropdown and amount input).

MoneyInput.isTouched({ amount: true, currencyCode: true }); // -> true

MoneyInput.isTouched({ amount: true }); // -> false
MoneyInput.isTouched({ currencyCode: true }); // -> false
MoneyInput.isTouched({ amount: false, currencyCode: false }); // -> false
MoneyInput.isTouched({}); // -> false

MoneyInput.getCurrencyDropdownId

getCurrencyDropdownId(idPrefix)

Returns the id of the currency dropdown. This is useful in case you want to create a label for the input field. You can use it as

MoneyInput.getCurrencyDropdownId('price');
// -> "price.currencyCode"

MoneyInput.getAmountInputId(idPrefix)

Returns the id of the amount input. This is useful in case you want to create a label for the input field. You can use it as

MoneyInput.getAmountInputId('price');
// -> "price.amount"

MoneyInput.isHighPrecision

The isHighPrecision function will return true when a MoneyInput value is passed for which the number of fraction digits of the amount exceeds the number of fraction digits the supplied currency usually uses.

The function may not be called with empty money values. It will throw in those cases.

MoneyInput.isHighPrecision({ amount: '2.00', currencyCode: 'EUR' }, 'en'); // -> false
MoneyInput.isHighPrecision({ amount: '2.001', currencyCode: 'EUR' }, 'en'); // -> true
MoneyInput.isHighPrecision({ amount: '2.001', currencyCode: 'EUR' }, 'de'); // -> false
MoneyInput.isHighPrecision({ amount: '2,001', currencyCode: 'EUR' }, 'de'); // -> true
MoneyInput.isHighPrecision({ amount: '', currencyCode: 'EUR' }, 'en'); // -> throws

Examples

Here's an example of how MoneyInput would be used inside a form.

import { IntlProvider } from 'react-intl';
import { Formik } from 'formik';
import omitEmpty from 'omit-empty-es';
import { ErrorMessage } from '@commercetools-uikit/messages';
import MoneyInput from '@commercetools-uikit/money-input';

const currencies = ['EUR', 'USD', 'AED', 'KWD'];

// the existing document, e.g. from the database
const doc = {
  somePrice: {
    type: 'centPrecision',
    currencyCode: 'EUR',
    centAmount: 4200,
    fractionDigits: 2,
  },
};

// A function to convert a document to form values.
const docToFormValues = (aDoc) => ({
  // The parseMoneyValue function will turn a MoneyValue into a
  // value the MoneyInput component can handle ({ amount, currencyCode })
  somePrice: MoneyInput.parseMoneyValue(aDoc.somePrice),
});

// a function to convert form values back to a document
const formValuesToDoc = (formValues, locale) => ({
  // The convertToMoneyValue function will turn a MoneyInput
  // value into a value the API can handle
  // It automatically converts to centPrecision or highPrecision
  // depending on the number of supplied fraction digits and the
  // used currency code.
  // If you want to forbid highPrecision, then the form's validation
  // needs to add an error when it sees a highPrecision price.
  // See example below
  somePrice: MoneyInput.convertToMoneyValue(formValues.somePrice, locale),
});

const validate = (formValues, locale) => {
  const errors = { somePrice: {} };
  const moneyValue = MoneyInput.convertToMoneyValue(
    formValues.somePrice,
    locale
  );
  // convertToMoneyValue returns null whenever the value is invalid
  if (!moneyValue) {
    errors.somePrice.missing = true;
  } else if (moneyValue.type === 'highPrecision') {
    // This form does not allow highPrecision prices
    errors.somePrice.highPrecision = true;
  }
  return omitEmpty(errors);
};
const initialValues = docToFormValues(doc);

return (
  <Formik
    initialValues={initialValues}
    validate={validate}
    onSubmit={(formValues) => {
      // doc will contain "somePrice" holding a MoneyValue,
      // ready to be consumed by the API
      const nextDoc = formValuesToDoc(formValues);
      console.log(nextDoc);
    }}
    render={({
      values,
      errors,
      touched,
      setFieldValue,
      setFieldTouched,
      handleSubmit,
      isSubmitting,
    }) => (
      <form onSubmit={handleSubmit}>
        <MoneyInput
          value={values.somePrice}
          currencies={currencies}
          onBlur={() => setFieldTouched('somePrice')}
          isDisabled={isSubmitting}
          onChange={(value) => setFieldValue('somePrice', value)}
          hasError={
            MoneyInput.isTouched(touched.somePrice) && Boolean(errors.somePrice)
          }
          horizontalConstraint={10}
        />
        {touched.somePrice && errors.somePrice && errors.somePrice.missing && (
          <ErrorMessage>This field is required!</ErrorMessage>
        )}
        {touched.somePrice &&
          errors.somePrice &&
          errors.somePrice.highPrecision && (
            <ErrorMessage>
              High precision prices are not supported here!
            </ErrorMessage>
          )}
        <button type="submit">Submit</button>
      </form>
    )}
  />
);
16.5.0

10 months ago

16.9.0

6 months ago

16.7.3

8 months ago

16.7.2

8 months ago

16.7.1

8 months ago

16.7.0

8 months ago

16.7.5

7 months ago

16.7.4

7 months ago

16.10.0

5 months ago

16.6.1

8 months ago

16.6.0

8 months ago

16.4.1

10 months ago

16.8.0

6 months ago

16.11.0

5 months ago

16.4.0

10 months ago

16.3.0

10 months ago

16.2.1

11 months ago

16.2.0

11 months ago

16.1.1

11 months ago

16.1.0

12 months ago

15.15.0

1 year ago

15.15.1

1 year ago

16.0.0

1 year ago

15.13.2

1 year ago

15.14.3

1 year ago

15.14.1

1 year ago

15.14.2

1 year ago

15.14.0

1 year ago

15.13.1

1 year ago

15.13.0

1 year ago

15.12.0

1 year ago

15.9.0

1 year ago

15.10.0

1 year ago

15.11.2

1 year ago

15.11.0

1 year ago

15.11.1

1 year ago

15.7.0

1 year ago

15.8.0

1 year ago

15.5.0

1 year ago

15.5.1

1 year ago

15.6.0

1 year ago

15.4.0

1 year ago

15.3.0

2 years ago

15.2.4

2 years ago

15.2.1

2 years ago

15.2.2

2 years ago

15.2.3

2 years ago

15.1.1

2 years ago

15.1.2

2 years ago

15.1.0

2 years ago

15.2.0

2 years ago

15.0.0

2 years ago

14.0.2

2 years ago

14.0.3

2 years ago

14.0.6

2 years ago

13.0.4

2 years ago

14.0.0

2 years ago

14.0.1

2 years ago

13.0.2

2 years ago

13.0.3

2 years ago

13.0.0

2 years ago

13.0.1

2 years ago

12.2.9

2 years ago

12.2.5

2 years ago

12.2.6

2 years ago

12.2.7

2 years ago

12.2.4

3 years ago

12.2.3

3 years ago

12.2.2

3 years ago

12.2.1

3 years ago

12.2.0

3 years ago

12.1.0

3 years ago

12.0.12

3 years ago

12.0.8

3 years ago

12.0.7

3 years ago

12.0.3

3 years ago

12.0.4

3 years ago

12.0.6

3 years ago

12.0.2

3 years ago

12.0.0

3 years ago

11.3.0

3 years ago

11.2.1

3 years ago

11.2.0

3 years ago

11.1.0

3 years ago

11.0.2

3 years ago

11.0.1

3 years ago

10.47.4

3 years ago

10.47.3

3 years ago

10.47.0

3 years ago

10.46.3

3 years ago

10.46.2

3 years ago

10.46.1

3 years ago

10.45.0

3 years ago

10.44.4

3 years ago

10.44.3

3 years ago

10.44.2

3 years ago

10.44.1

3 years ago

10.44.0

3 years ago

10.43.3

3 years ago

10.43.2

3 years ago

10.43.1

3 years ago

10.42.3

3 years ago

10.42.2

3 years ago

10.42.0

3 years ago

10.42.1

3 years ago

10.41.0

3 years ago

10.40.0

3 years ago

10.40.1

3 years ago

10.39.8

3 years ago

10.39.7

3 years ago

10.39.6

3 years ago

10.39.4

3 years ago

10.39.3

3 years ago

10.39.2

3 years ago

10.39.1

3 years ago

10.38.0

3 years ago

10.37.1

4 years ago

10.36.0

4 years ago

10.35.2

4 years ago

10.35.1

4 years ago

10.35.0

4 years ago

10.34.0

4 years ago

10.33.0

4 years ago

10.32.0

4 years ago

10.31.0

4 years ago

10.30.1

4 years ago

10.27.0

4 years ago

10.24.0

4 years ago

10.23.0

4 years ago

10.22.0

4 years ago

10.21.0

4 years ago

10.20.0

4 years ago

10.19.0

4 years ago

10.18.7-canary.5

4 years ago

10.18.7-canary.6

4 years ago

10.18.7-canary.7

4 years ago

10.18.7-canary.4

4 years ago

10.18.7-canary.3

4 years ago

10.18.7-canary.2

4 years ago

10.18.7-canary.1

4 years ago

10.18.7-canary.0

4 years ago

10.18.6-canary.1

4 years ago

10.18.6-canary.0

4 years ago

10.18.5-canary.4

4 years ago

10.18.5-canary.3

4 years ago

10.18.5-canary.2

4 years ago

10.18.5-canary.1

4 years ago

10.18.5-canary.0

4 years ago

10.18.4

4 years ago

10.18.4-canary.9

4 years ago

10.18.4-canary.8

4 years ago

10.18.4-canary.7

4 years ago

10.18.4-canary.6

4 years ago

10.18.4-canary.3

4 years ago

10.18.4-canary.4

4 years ago

10.18.4-canary.5

4 years ago

10.18.4-canary.1

4 years ago

10.18.4-canary.2

4 years ago

10.18.4-canary.0

4 years ago

10.18.3-canary.2

4 years ago

10.18.3-canary.3

4 years ago

10.18.3-canary.1

4 years ago

10.18.3-canary.0

4 years ago

10.18.2

4 years ago

10.18.2-canary.3

4 years ago

10.18.2-canary.2

4 years ago

10.18.2-canary.1

4 years ago

10.17.1-canary.3

4 years ago

10.17.1-canary.2

4 years ago

10.18.1-canary.0

4 years ago

10.18.2-canary.0

4 years ago

10.18.0

4 years ago

10.17.1-canary.1

4 years ago

10.18.0-alpha.0

4 years ago

10.17.0

4 years ago

10.17.1-canary.0

4 years ago

10.16.1-canary.8

4 years ago

10.16.1-canary.7

4 years ago

10.16.1-canary.5

4 years ago

10.16.1-canary.6

4 years ago

10.16.1-canary.4

4 years ago

10.16.1-canary.3

4 years ago

10.16.1-canary.2

4 years ago

10.16.1-canary.1

4 years ago

10.16.1-canary.0

4 years ago

10.16.0

4 years ago

10.15.2-canary.4

4 years ago

10.15.2-canary.0

4 years ago

10.15.2-canary.2

4 years ago

10.15.2-canary.3

4 years ago

10.15.1

4 years ago

10.15.1-canary.6

4 years ago

10.15.1-canary.4

4 years ago

10.15.0

4 years ago

10.14.3-canary.4

4 years ago

10.14.1

4 years ago

10.14.1-canary.7

4 years ago

10.13.1-canary.6

4 years ago

10.13.0

4 years ago

11.0.0-alpha.11

4 years ago

11.0.0-alpha.10

4 years ago

11.0.0-alpha.9

4 years ago

11.0.0-alpha.6

4 years ago

11.0.0-alpha.7

4 years ago

11.0.0-alpha.8

4 years ago

11.0.0-alpha.5

4 years ago

11.0.0-alpha.4

4 years ago

11.0.0-alpha.3

4 years ago

11.0.0-alpha.2

4 years ago

11.0.0-alpha.1

4 years ago

11.0.0-alpha.0

4 years ago