Socket
Socket
Sign inDemoInstall

react-native-globalize

Package Overview
Dependencies
582
Maintainers
1
Versions
53
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    react-native-globalize

Globalization helper for React Native


Version published
Maintainers
1
Install size
11.5 MB
Created

Readme

Source

React Native Globalize

NPM Version Build Status Coverage Status Dependency Status Dev Dependency Status

Simple globalization library for React Native. Provides various formatting functions as well as easy-to-use React Native components.

About React Native Globalize

React Native Globalize can format (and parse) numbers, dates, currency, and messages (using the ICU message pattern) with the correct plural rules for the language/locale. This functionality depends on CLDR data for the languages/locales being used. By default, many (but not all) languages/locales and currencies are loaded by default and you can pass additional CLDR data in various ways. However, it is recommended to customize the CLDR data (see below) to only include what you need in order to minimize the bundle size and startup time.

Default Locales & Currencies

const locales = [
  'am',           // Amharic
  'ar',           // Arabic
  'bg',           // Bulgarian
  'bn',           // Bengali
  'ca',           // Catalan
  'cs',           // Czech
  'da',           // Danish
  'de',           // German
  'el',           // Greek
  'en',           // English (United States)
  'en-GB',        // English (Great Britain)
  'es',           // Spanish
  'es-419',       // Spanish (Latin America & Caribbean)
  'et',           // Estonian
  'fa',           // Farsi
  'fi',           // Finnish
  'fil',          // Filipino
  'fr',           // French
  'gu',           // Gujarati
  'he',           // Hebrew
  'hi',           // Hindi
  'hr',           // Croatian
  'hu',           // Hungarian
  'id',           // Indonesian
  'it',           // Italian
  'ja',           // Japanese
  'kn',           // Kannada
  'ko',           // Korean
  'lt',           // Lithuanian
  'lv',           // Latvian
  'ml',           // Malayalam
  'mr',           // Marathi
  'ms',           // Malay
  'nb',           // Norwegian
  'nl',           // Dutch
  'pl',           // Polish
  'pt',           // Portuguese
  'pt-PT',        // Portuguese (Portugal)
  'ro',           // Romanian
  'ru',           // Russian
  'sk',           // Slovak
  'sl',           // Slovenian
  'sr',           // Serbian
  'sv',           // Swedish
  'sw',           // Swahili
  'ta',           // Tamil
  'te',           // Telugu
  'th',           // Thai
  'tr',           // Turkish
  'uk',           // Ukrainian
  'vi',           // Vietnamese
  'zh',           // Chinese
  'zh-Hans',      // Chinese (Simplified)
  'zh-Hant',      // Chinese (Traditional)
];

const currencies = [
  'CAD',          // Canadian Dollar
  'EUR',          // Euro
  'GBP',          // British Pound
  'USD',          // US Dollar
];

Customizing the included languages and/or currencies

  1. Fork this repo.
  2. Edit the locales and currencies arrays in gulpfile.js to suit your needs.
  3. Run gulp cldr.
  4. The lib/cldr.json file is now your own customized version with only what you need.

Installation

After installing using npm/yarn, place FormattedProvider at the root of your application to propagate the required context to all components. Then use any of the included Formatted* components anywhere in your application or access the formatting functions directly using the withGlobalize HOC.

NOTE: Version 2.0.0 and up requires React >= 16.3.1 & React Native >= 0.55.0!

Usage

FormattedProvider

Props
PropTypeDefaultDescription
localeStringenThe language/locale to be used for formatting.
currencyStringUSDThe default currency code to be used for currency formatting.
messagesObjectICU-formatted messages for use with FormattedMessage and getMessageFormatter.
cldrArrayAdditional CLDR data to load (e.g. cldr={[require('path/to/file.json'), require('path/to/anotherFile.json')]}).
localeFallbackBooleanfalseAutomatically attempt to find a fallback when CLDR data for the selected locale is missing (e.g. en_NZ -> en).
warnOnMissingMessageBooleantrueDisplay a warning message when a message key is missing.
import { FormattedProvider } from 'react-native-globalize';

const Messages = {
  en: {
    hello: 'Hello',
  },
  es: {
    hello: 'Hola',
  },
};

class MyApp extends PureComponent {
  render() {
    return (
      <FormattedProvider locale="en" currency="USD" messages={Messages}>
        <App />
      </FormattedProvider>
    )
  }
}

FormattedCurrency

Props
PropTypeDefaultDescription
valueNumberRequired. The number you want to format.
currencyStringDefaults to currency set on FormattedWrapper.
maximumFractionDigitsIntNon-negative integer indicating the maximum fraction digits to be shown. Numbers will be rounded or padded with trailing zeroes as necessary.
minimumFractionDigitsIntNon-negative integer indicating the minimum fraction digits to be shown. Numbers will be rounded or padded with trailing zeroes as necessary.
minimumIntegerDigitsIntNon-negative integer indicating the minimum integer digits to be shown. Numbers will be padded with leading zeroes as necessary.
maximumSignificantDigitsIntNon-negative integer indicating the maximum significant digits to be shown. Numbers will be rounded or padded with trailing zeroes as necessary.
minimumSignificantDigitsIntNon-negative integer indicating the minimum significant digits to be shown. Numbers will be rounded or padded with trailing zeroes as necessary.
numberStyleStringsymbolFormatting style to use when displaying currency. Values: symbol ($1.00), accounting, code (1.00 USD), or name (1.00 US dollar).
roundStringroundControls the rounding method used when rouding required (e.g. when using maximumFractionDigits). Values: ceil, floor, round, or truncate.
styleTextStyleStyles to apply to resulting Text node.
useGroupingBooleantrueWhether a grouping separator should be used.
accessibilityLabelStringAccessibility label for screen readers.
adjustsFontSizeToFitBooleanfalseWhether font size should be scaled down to fit.
allowFontScalingBooleantrueWhether fonts should scale to respect Text Size accessibility settings.

Note: Using maximumFractionDigits, minimumFractionDigits, ..., useGrouping overrides the language default derived from CLDR.

import { FormattedCurrency } from 'react-native-globalize';

class MyComponent extends PureComponent {
  render() {
    return (
      <FormattedCurrency
        value={9.99}
        currency="USD"
        style={{ color: 'red' }} />
    );
  }
}
// $9.99

FormattedDate

Props
PropTypeDefaultDescription
valueDateRequired. The date object you want to format.
dateStringOne of: full, long, medium, short. Outputs just a date (e.g. Monday, November 1, 2010).
datetimeStringOne of: full, long, medium, short. Outputs a datetime (e.g. Monday, November 1, 2010 at 5:55:00 PM GMT-02:00).
skeletonStringDate format skeleton. See the CLDR documentation. Not all options work
styleTextStyleStyles to apply to resulting Text node.
timeStringOne of: full, long, medium, short. Outputs just a time (e.g. 5:55:00 PM GMT-02:00).
accessibilityLabelStringAccessibility label for screen readers.
adjustsFontSizeToFitBooleanfalseWhether font size should be scaled down to fit.
allowFontScalingBooleantrueWhether fonts should scale to respect Text Size accessibility settings.

Only ONE of skeleton, date, time, and datetime should be specified.

import { FormattedDate } from 'react-native-globalize';

class MyComponent extends PureComponent {
  render() {
    return (
      <FormattedDate
        value={new Date()}
        style={{ color: 'red' }}
        skeleton="yMd" />
    );
  }
}
// 12/31/2015

FormattedMessage

Format a message based on the ICU message format pattern and variables.

Props
PropTypeDefaultDescription
messageArray/StringRequired. The key of the message you want to format. Can be passed as a string (e.g. test/hello) or an array (e.g. ['test', 'hello']).
defaultMessageStringA string to display if the message key does not exist. Otherwise, the message key itself will be displayed.
styleTextStyleStyles to apply to resulting Text node.
valuesObject{}Variables for replacement/formatting.
accessibilityLabelStringAccessibility label for screen readers.
adjustsFontSizeToFitBooleanfalseWhether font size should be scaled down to fit.
allowFontScalingBooleantrueWhether fonts should scale to respect Text Size accessibility settings.
  • Values/variables can also be passed as props. Any additional props other than the 4 above will be merged with the values object. Note: Specific props will override the values object if both are given and keys collide.
  • Values can also be components. See the last example below.
  • See ICU message formatting guidelines for more info.
// Messages added via FormattedWrapper
const Messages = {
  en: {
    hello: 'Hey {first} {middle} {last},',
    test: {
      select: '{gender, select, female {{host} invites {guest} to her party} male {{host} invites {guest} to his party} other {{host} invites {guest} to their party}}',
      plural: 'You have {count, plural, one {one task} other {{count} tasks}} remaining',
      component: 'Hey {name}, you asked me to remind you about {item} at {time}!',
    },
  },
};

// Example 1
import { FormattedMessage } from 'react-native-globalize';

class MyComponent extends PureComponent {
  render() {
    return (
      <FormattedMessage
        message="hello"
        first="John"
        middle="William"
        last="Smith"
        style={{ color: 'red' }} />
    );
  }
}
// Hey John William Smith,

// Example 2
import { FormattedMessage } from 'react-native-globalize';

class MyComponent extends PureComponent {
  render() {
    return (
      <FormattedMessage
        message="test/select"
        values={{ gender: 'male', host: 'Josh', guest: 'Andrea' }}
        style={{ color: 'red' }} />
    );
  }
}
// Josh invites Andrea to his party

// Example 3
import { FormattedMessage } from 'react-native-globalize';

class MyComponent extends PureComponent {
  render() {
    return (
      <FormattedMessage
        message={['test', 'select']}
        gender="female"
        host="Jennifer"
        guest="Michael"
        style={{ color: 'red' }} />
    );
  }
}
// Jennifer invites Michael to her party

// Example 4
import { FormattedMessage } from 'react-native-globalize';

class MyComponent extends PureComponent {
  render() {
    return (
      <FormattedMessage
        message="test/plural"
        values={{ count: 4 }}
        style={{ color: 'red' }} />
    );
  }
}
// You have 4 tasks remaining

// Example 5
import { FormattedMessage } from 'react-native-globalize';

class MyComponent extends PureComponent {
  render() {
    return (
      <FormattedMessage
        message="test/component"
        name="Josh"
        item="buying groceries"
        time={<FormattedDate value={new Date()} time="short" />} />
    );
  }
}
// Hey Josh, you asked me to remind you about buying groceries at 4:00 PM

FormattedNumber

Props
PropTypeDefaultDescription
valueNumberRequired. The number you want to format.
styleTextStyleStyles to apply to resulting Text node.
maximumFractionDigitsIntNon-negative integer indicating the maximum fraction digits to be shown. Numbers will be rounded or padded with trailing zeroes as necessary.
minimumFractionDigitsIntNon-negative integer indicating the minimum fraction digits to be shown. Numbers will be rounded or padded with trailing zeroes as necessary.
minimumIntegerDigitsIntNon-negative integer indicating the minimum integer digits to be shown. Numbers will be padded with leading zeroes as necessary.
maximumSignificantDigitsIntNon-negative integer indicating the maximum significant digits to be shown. Numbers will be rounded or padded with trailing zeroes as necessary.
minimumSignificantDigitsIntNon-negative integer indicating the minimum significant digits to be shown. Numbers will be rounded or padded with trailing zeroes as necessary.
numberStyleStringsymbolFormatting style to use when displaying currency. Values: symbol ($1.00), accounting, code (1.00 USD), or name (1.00 US dollar).
roundStringroundControls the rounding method used when rouding required (e.g. when using maximumFractionDigits). Values: ceil, floor, round, or truncate.
useGroupingBooleantrueWhether a grouping separator should be used.
accessibilityLabelStringAccessibility label for screen readers.
adjustsFontSizeToFitBooleanfalseWhether font size should be scaled down to fit.
allowFontScalingBooleantrueWhether fonts should scale to respect Text Size accessibility settings.

Note: Using maximumFractionDigits, minimumFractionDigits, ..., useGrouping overrides the language default derived from CLDR.

import { FormattedNumber } from 'react-native-globalize';

class MyComponent extends PureComponent {
  render() {
    return (
      <FormattedNumber
        value={1.5}
        minimumFractionDigits={2}
        style={{ color: 'red' }} />
    )
  }
}
// 1.50

// Arabic (ar) selected
import { FormattedNumber } from 'react-native-globalize';

class MyComponent extends PureComponent {
  render() {
    return (
      <FormattedNumber
        value={3.141592}
        style={{ color: 'red' }} />
    )
  }
}
// ٣٫١٤٢

FormattedPlural

Props
PropTypeDefaultDescription
valueNumberRequired. The value you want to base plural selection on.
styleTextStyleStyles to apply to resulting Text node.
typeStringcardinalControl plural type. Values: cardinal or ordinal.
otherNodeNode to output when plural type is other or when node for type is not specified.
zeroNodeNode to output when plural type is zero.
oneNodeNode to output when plural type is one.
twoNodeNode to output when plural type is two.
fewNodeNode to output when plural type is few.
manyNodeNode to output when plural type is many.
accessibilityLabelStringAccessibility label for screen readers.
adjustsFontSizeToFitBooleanfalseWhether font size should be scaled down to fit.
allowFontScalingBooleantrueWhether fonts should scale to respect Text Size accessibility settings.
import { FormattedPlural } from 'react-native-globalize';

class MyComponent extends PureComponent {
  render() {
    return (
      <FormattedPlural
        value={0}
        zero={<Text>:(</Text>}
        other={<Text>:)</Text>} />
    );
  }
}
// :(

FormattedRelativeTime

Props
PropTypeDefaultDescription
valueDateRequired. The date you want to use to compute the difference from.
unitStringRequired. One of: best, second, minute, hour, day, week, month, year.
formMixedOne of: short, narrow, 0, false. Change output type.
styleTextStyleStyles to apply to resulting Text node.
accessibilityLabelStringAccessibility label for screen readers.
adjustsFontSizeToFitBooleanfalseWhether font size should be scaled down to fit.
allowFontScalingBooleantrueWhether fonts should scale to respect Text Size accessibility settings.
import { FormattedRelativeTime } from 'react-native-globalize';

class MyComponent extends PureComponent {
  render() {
    return (
      <FormattedRelativeTime
        value={myDateObject}
        unit="best"
        style={{ color: 'red' }} />
    );
  }
}
// 2 days ago

FormattedTime

See FormattedDate. All props and functionality are identical.

FormattedUnit

Props
PropTypeDefaultDescription
valueNumberRequired. The number you want to format.
unitStringRequired. The unit to be formatted (e.g. day, mile-per-hour). See main.{locale}.units in cldr.json for options.
formMixedOne of: long, short, narrow. Change output type.
numberFormatterFunctionA custom number formatter function from getNumberFormatter for customizing how number is displayed in output.
styleTextStyleStyles to apply to resulting Text node.
accessibilityLabelStringAccessibility label for screen readers.
adjustsFontSizeToFitBooleanfalseWhether font size should be scaled down to fit.
allowFontScalingBooleantrueWhether fonts should scale to respect Text Size accessibility settings.
// Example 1
import { FormattedUnit } from 'react-native-globalize';

class MyComponent extends PureComponent {
  render() {
    return (
      <FormattedUnit
        unit="mile-per-hour"
        value={75}
      />
    )
  }
}
// 75 miles per hour

// Example 2
import { FormattedUnit } from 'react-native-globalize';

class MyComponent extends PureComponent {
  render() {
    // Requires `withGlobalize` HOC to inject globalize prop
    const numberFormatter = this.props.globalize.getNumberFormatter({
      minimumFractionDigits: 2,
      useGrouping: false,
    });

    return (
      <FormattedUnit
        form="narrow"
        numberFormatter={numberFormatter}
        unit="area-square-mile"
        value={5000}
      />
    )
  }
}
// 5000.00mi²

withGlobalize

You can access formatting functions directly should you need programmatic access to the results or if a component is not appropriate. The withGlobalize HOC will inject a globalize prop into your component, allowing you to access the same methods the Formatted* components use. For this to work, you must still have FormattedProvider at the root of you application.

import { withGlobalize } from 'react-native-globalize';

class MyComponent extends PureComponent {
  myFunction() {
    const dateFormatter = this.props.globalize.getDateFormatter({skeleton: 'yMd'});
    const formattedDate = dateFormatter(new Date());

    const currencyFormatter = this.props.globalize.getCurrencyFormatter('USD', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
    const formattedCurrency = currencyFormatter(9.99);

    const currencySymbol = this.props.globalize.getCurrencySymbol();
  }
}

export default withGlobalize(MyComponent);

Globalize

A few static methods are also available on the Globalize class. You can check whether CLDR data has been loaded for a given locale, get an array of all loaded locales, load additional CLDR data, and load additional ICU-formatted messages. Check out the examples below.

import { Globalize } from 'react-native-globalize';

// Check if a locale has CLDR data
Globalize.localeIsLoaded('en');
// true

// Get an array of all loaded locales
Globalize.availableLocales();
// [ 'am', 'ar', ... ]

// Load additional CLDR data
Globalize.load([require('path/to/cldr/file.json')]);

// Load additional messages
Globalize.loadMessages({
  en: {
    test: 'Hi Josh!',
  },
});

License

 Copyright (c) 2015-2019 Josh Swan

 Licensed under the The MIT License (MIT) (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

    https://raw.githubusercontent.com/joshswan/react-native-globalize/master/LICENSE

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

Keywords

FAQs

Last updated on 10 Mar 2019

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc