Socket
Socket
Sign inDemoInstall

react-native-globalize

Package Overview
Dependencies
3
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
Created

Readme

Source

#React Native Globalize NPM Version Build Status Dependency Status Dev Dependency Status

Simple globalization library for React Native. Provides access to all formatting options as well as easy-to-use React Native components.

How does it work?

Because it's based on the jQuery Globalize project, React Native Globalize can format and parse numbers, format and parse dates, format currency, and format messages (using the ICU message pattern) using the correct plural rules for the language/locale. Take a look at https://github.com/jquery/globalize for more information.

The important thing to note is all this functionality depends entirely on CLDR data. While a huge number of languages and locales are available in this data, only some are loaded by default. This is done for performance reasons as React Native currently bundles everything into one large JS bundle, and with CLDR data being hundreds of megabytes, it causes some issues. The default languages are listed below, but you can always pass additional CLDR data if you need additional language/locale support:

var locales = [
  'am',           // Amharic
  'ar',           // Arabic
  'bg',           // Bulgarian
  'bn',           // Bengali
  'ca',           // Catalan
  'cs',           // Czech
  'da',           // Danish
  'de',           // German
  'el',           // Greek
  'en',           // English
  'en-GB',        // English (Great Britain)
  'en-US',        // English (United States)
  'es',           // Spanish
  'es-419',       // Spanish (Latin America & Caribbean)
  'et',           // Estonian
  'fa',           // Persian
  '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)
];

Usage

Use FormattedWrapper at the root of your application to propagate the required context to all components. Alternatively, include getChildContext() in your own component (see FormattedWrapper for an example). Then use any of the included components or access the formatting functions directly from the React Context (see below) anywhere in your application.

FormattedWrapper

Props
PropTypeDefaultDescription
localeStringenThe language/locale to be used for formatting.
currencyString'USD'The 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).
import { FormattedWrapper } from 'react-native-globalize';

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

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

FormattedCurrency

Props
PropTypeDefaultDescription
valueNumberRequired. The number you want to format.
currencyStringDefaults to currency set on FormattedWrapper.
styleTextStyleStyles to apply to resulting Text node.
minimumFractionDigitsIntNon-negative integer indicating the minimum fraction digits to be shown. Numbers will be rounded or padded with trailing zeroes as necessary. This overrides the default minimum fraction digits derived from CLDR.
maximumFractionDigitsIntNon-negative integer indicating the maximum fraction digits to be shown. Numbers will be rounded or padded with trailing zeroes as necessary. This overrides the default maximum fraction digits derived from CLDR.
roundStringroundRounding method: ceil, floor, round, or truncate.
useGroupingBooleantrueWhether a grouping separator should be used. This overrides the language default derived from CLDR.
import { FormattedCurrency } from 'react-native-globalize';

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

FormattedDate

Props
PropTypeDefaultDescription
valueDateRequired. The date object you want to format.
styleTextStyleStyles to apply to resulting Text node.
skeletonStringDate format skeleton. See the CLDR documentation. Not all options work
dateStringOne of: full, long, medium, short. Outputs just a date (e.g. Monday, November 1, 2010).
timeStringOne of: full, long, medium, short. Outputs just a time (e.g. 5:55:00 PM GMT-02:00).
datetimeStringOne of: full, long, medium, short. Outputs a datetime (e.g. Monday, November 1, 2010 at 5:55:00 PM GMT-02:00).

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

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

class MyComponent extends Component {
  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']).
valuesObject{}Variables for replacement/formatting.
styleTextStyleStyles to apply to resulting Text node.
  • Values/variables can also be passed as props. Any additional props other than the 3 above will be merged with the values object (props will overwrite values in the 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 Component {
  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 Component {
  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 Component {
  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 Component {
  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 Component {
  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.
minimumFractionDigitsIntNon-negative integer indicating the minimum fraction digits to be shown. Numbers will be rounded or padded with trailing zeroes as necessary. This overrides the default minimum fraction digits derived from CLDR.
maximumFractionDigitsIntNon-negative integer indicating the maximum fraction digits to be shown. Numbers will be rounded or padded with trailing zeroes as necessary. This overrides the default maximum fraction digits derived from CLDR.
roundStringroundRounding method: ceil, floor, round, or truncate.
useGroupingBooleantrueWhether a grouping separator should be used. This overrides the language default derived from CLDR.
import { FormattedNumber } from 'react-native-globalize';

class MyComponent extends Component {
  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 Component {
  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.
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.
import { FormattedPlural } from 'react-native-globalize';

class MyComponent extends Component {
  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.
unitString*** Required.*** One of: best, second, minute, hour, day, week, month, year.
styleTextStyleStyles to apply to resulting Text node.
formMixedOne of: short, narrow, 0, false. Change output type.
import { FormattedRelativeTime } from 'react-native-globalize';

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

FormattedTime

See FormattedDate. All props and functionality are identical.

Context

You can access formatting functions via the context should you need programmatic access to the results or if a component is not appropriate. For this to work, you must still have FormattedWrapper at the root of you application, or you must be providing an alternative getChildContext in a parent component.

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

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

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

MyComponent.contextTypes = {
  globalize: PropTypes.globalizeShape,
};

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-2016 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 27 May 2016

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