Giter Club home page Giter Club logo

react-native-globalize's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

react-native-globalize's Issues

gulp cldr error

I am forking the repo and run 'gulp cldr', with

const locales = [
  'en',           // English (United States)
  'id'           // Indonesian
];

const currencies = [
  'IDR'          // Indonesia Rupiah
];

But, got an error "TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type undefined".

Screen Shot 2019-03-09 at 17 05 58

How to resolve this?

Currency Digits

Hello!

Is there any way to set the digits? I noticed it just accept float/integer, so I can't use "toFixed()".
Also, it can't bet set globally. Sometimes I need 2 digits, and sometimes no digits at all.

Thanks!

Globalize doesn't show the good message

I have this code :


import React, { Component } from 'react';
import {Text,View} from 'react-native';
import { FormattedWrapper,FormattedMessage,Globalize,PropTypes } from 'react-native-globalize';
const Messages = {
  fr:{
    hello:'bonjour'
  },
  es:{
    hello:'hola'
  }
}
export default class TestScene extends Component {


  constructor(props) {
    super(props);
  }
  render(){
    return (
      <FormattedWrapper locale="es" messages={Messages}>
      <View style={{flex:1, margin:30}}>
        <Text>{this.context.globalize.getMessageFormatter('hello')()}</Text>
      </View>
      </FormattedWrapper>

    );
  }
}
TestScene.contextTypes = {
  globalize: PropTypes.globalizeShape,
};

That show me "Hello" on my device instead of "hola". It is normal ?

Cldrjs errors with React 0.26.2

My project works with 0.25 (thanks for the recent fixes!), but upgrading to 0.26.2 (with react 15.0.2), I get a different set of problems:

Cannot read property 'init' of undefined

<unknown>
  event.js @ 547:0: superInit = Cldr.prototype.init;
pathNormalize
  event.js @ 22:0: module.exports = factory( require( "cldrjs" ) );
<unknown>
  event.js @ 25:0: factory( Cldr );
loadModuleImplementation
  require.js @ 100:0:  ....
...more require.js...
<unknown>
  node_main.js @ 20:0: require( "./cldr/event" );
...more require.js...

Looks like importing cldrjs imports node_main.js imports cldr/event.js imports cldrjs (which is technically a cycle). In theory the fact that node_main.js sets module.exports before importing cldr/event.js should help?

Regardless, when node_main.js sets module.exports, it is a valid Cldrjs class object. Unfortunately, when cldr/event.js imports it via cldrjs, it is an empty object. I have no idea why this is, or why this apparently changed when I upgraded from react-native 0.25.x to 0.26.2.

It also looks to be entirely within cldrjs, but again given that it's the react-native upgrade is triggering this problem, I doubt the cldrjs folks will care much about the problem. So I'm filing it here in react-native-globalize, as that's the import that manifests itself to me and the border between cldrjs and RN.

Idea: Not only <text>

Hi,

this is a feature idea. Ever thought of using your project to not only produce formatted text but also formatted input fields?

Cheers, Sven

Is there a way this library can detect the locale automatically?

The reason I would want to use something like this is to format numbers according to the user's locale.
But the example in the README shows the locale being explicitly set at the root of the application. This doesn't seem to be very useful IMO.

<FormattedProvider locale="en"

I must be missing something...

Support for getting the currency symbol directly.

Hi,

Thanks for the library, it's working great 👍 . I was wondering whether there is an option to get the currency symbol directly so I can display it in other UI elements as well. For instance a settings screen showing the active currency or a label next to a monetary input field.

Thanks in advance,

Rick

Globalize compiler?

I see that jquery supports a Globalize Compiler, to help build JS files that contain just the minimal bits necessary (instead of needing to embed the fat, or even semi-trimmed cldr.json). Curious if you've explored using this at all within a react-native-globalize app?

I'm trying to decide between react-intl (based on formatjs stack, many more users, tentative RN support, but doesn't appear to optimize files well like RN-G's gulpfile does?) and react-native-globalize (based on globalize stack. the RN-G project has much less users/testing than R-I, but this Globalize Compiler seems like some nice hotness to have)

postinstall step failing on CircleCI

Using yarn on circleci version 4.0.0 of the package fails to build, giving the following output:

[4/4] Building fresh packages...
error /home/circleci/project/node_modules/react-native-globalize: Command failed.
Exit code: 1
Command: patch-package
Arguments: 
Directory: /home/circleci/project/node_modules/react-native-globalize
Output:
patch-package 6.2.0
Applying patches...
Error: Patch file found for package globalize which is not present at node_modules/@types/globalize
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

Typescript support

Hello.

Thank you for the project, it is a really necessary one.

As I can see, this project doesn't provide typings and there is no according @types/react-native-globalize package.

Do you plan to add typescript typings?

How add FormattedMessage on Picker Labels

Is there a way user FormattedMessage in Pickers Items Labels. I tried like

<Item label={<FormattedMessage message="Label1"/>} value={''}/>

But it show this Error:

malformed calls from js

Any fix?

Fallback locale does not fork

In case if we use locale that does not presented. For example:

loadMessages({
  'en': {
    welcome: 'Hallo, heute ist der {date}',
  }
})

And we use GlobalizeProvider with localeFallback: "en"

When user is in locale sv for example, we get the following error:

[RNGlobalize] CLDR data for the selected language/locale has not been loaded!

The reason, that in the code we have:

cfg.locale = (cfg.fallback && findFallbackLocale(cfg.locale)) as string;

It means if cfg.fallback is "en", we still try to findFallbackLocale for locale sv which does not exist

We need to change it to:

cfg.locale = (cfg.fallback && findFallbackLocale(cfg.fallback)) as string;

How to use useGlobalize with class component

Hello thanks for building this library, please I was wondering is there is a way to use with use globalized, with class component given that I already code the whole application using class component and am just trying to add multilanguage support and I can't convert my whole app to into functional component.

Thanks

Packager TimeoutError

Hello there!

I've been using rn-globabalize for a while, and it worked fine, but suddenly I can't start my app, and the react native packager is throwing this error:

Error: TimeoutError: transforming /Users/michael/dev/finances_pro/node_modules/react-native-globalize/lib/cldr.json took longer than 301 seconds.
You can adjust timeout via the 'transformTimeoutInterval' option
    at index.js:101:30
    at tryCallOne (/Users/michael/dev/finances_pro/node_modules/promise/lib/core.js:37:12)
    at /Users/michael/dev/finances_pro/node_modules/promise/lib/core.js:123:15
    at flush (/Users/michael/dev/finances_pro/node_modules/asap/raw.js:50:29)
    at _combinedTickCallback (node.js:376:9)
    at process._tickCallback (node.js:407:11)

I've changed nothing about the package, tried to update it but no lucky. When I removed all references to it in my code, the package runs fine.

For reference, I'm using React Native 0.25.1

Fallback language?

Firstly, thanks for the wonderful module.

Is there an option to set fallback language?

Right now I am using NativeModule to determine user ios locale NativeModules.SettingsManager.settings.AppleLocale.

When you don't have the defined language in your message bundle, you will get error such as this with release build. For instance, I didn't set 'en_TW' for my language json but did have 'en'

'RCTFatalException: Unhandled JS Exception: E_MISSING_MESSAGE_BUNDLE: Missing message bundle for localeen_TW.'

<FormattedMessage message={} / how to use array?

The Code:
I want to get the 'GENERAL' text from current loaded locale.

<FormattedMessage 
    message={['scenes', 'faq','title','sections',0,'title']}
    values={{ 
        newline: '\n',
    }}
/>

The Json :

en = {
    scenes: {
        faq: {
            title: 'Frequently Asked Questions',
            sections: [
                {
                    title: 'GENERAL',
                },
                {
                    title: 'ADVANCED',
                },
            ],
        },
    },
};

Thank you

getCurrencySymbol() with GlobalizeProvider throwing TypeError

It would be nice if when getCurrencySymbol is called with no arguments it would use the locale and currency loaded with GlobalizeProvider. Currently calling it with no arguments give the following error:

getCurrencySymbol
node_modules/react-native-globalize/dist/globalize/utils.js:40
  37 |     }
  38 |     const { currencies } = Cldr._raw.main[locale].numbers;
  39 |     const key = altNarrow ? 'symbol-alt-narrow' : 'symbol';
> 40 |     return ((_a = currencies) === null || _a === void 0 ? void 0 : _a[currencyCode][key]) || null;
  41 | }
  42 | export function logError(message, exception) {
  43 |     if (process.env.NODE_ENV !== 'production') {

Adding prefix

Hi,

Is it possible to add a prefix to FormattedNumber or FormattedCurrency?
I need to add an "%" to the number.

Thanks

'undefined is not an object' when using <FormattedDate>

Hi,

I'm new to the react-native space but I have stumbled on a problem that I cannot seem to workaround with this. When using the tag to render a simple test (I'm literally using your <FormattedDate value={new Date()} skeleton="yMMMdhm" /> example from the guide), I run into an error that complains about "undefined is not an object (evaluating 'this.context.globalize.getDateFormatter')". This is the message thrown back from a catch block I have in my render method.

The tag is being used within a class method that creates entries for a ScrollView - everything works perfectly until I try to use the FormattedDate tag. I moved the tag to be within the renderScene method that I am using to fill out the Navigator but the problem is exactly the same. It's almost as if something has dropped out of scope but the problem is not obvious to me.

I'm using v4.24 of Node, react-native 0.18.1, react-native-cli 0.1.10, and a Genymotion Android emulator configured for v6 API Level 23.

Thanks

How to change active locale programatically?

Hi,
I can't find a way to change active locale programmatically, I read the doc and issues on github to no luck, maybe I miss something?
Fyi, I have two locales in my App, I can access methods from the context, also with static methods. if I do:
this.context.globalize = new Globalize(alternateLocale);
it seem the locale changed briefly before it revert back (saw the text changed briefly).

RN Globalize not working when nested inside HoC

Reproducible demo repo:

Expo React native project.

https://github.com/haydump/test-globalize-hoc

Description

When nested with higher-order-component functions (for example connect from redux, and various from recompose), Components (FomattedMessages, etc..) will only render once with initial FormattedWrapper's locale, and won't re-render when locale changes

Environment

expo         v19
react-native 0.46
redux        3.7.2
recompose    0.25.0

Steps to Reproduce

Clone demo repo, yarn install or npm install. Open Expo XDE, open repo project. Then run on Simulator or Devices of your choice.
In App.js

      <Provider store={store}>
        <LocalizationWrapper>
          <View style={{flex: 1}}>
            <ExampleComponent style={{flex: 1, alignItems: 'center', justifyContent: 'center'}} />
            <ExampleHoC style={{flex: 1, alignItems: 'center', justifyContent: 'center'}} />
          </View>
        </LocalizationWrapper>
      </Provider>
  • LocalizationWrapper is FormattedWrapper wrapped with reducer to store and change locale.
  • ExampleComponent is a normal React component.
  • ExampleHoC is ExampleComponent wrapped in a simple connect from redux, no new props is added.

Actual Behavior

When run, a saga will start changing locale between en, th, zh every second.
ExampleComponent will change text accordingly, while ExampleHoC stays the same.

Expected Behavior

Higher-order-component ExampleHoC should re-render similar to ExampleComponent

Ability to use the "alt narrow" currency symbol

When I look in the CLDR json data, there is both symbol and symbol-alt-narrow keys

				"AUD": {
					"displayName": "Australian Dollar",
					"displayName-count-one": "Australian dollar",
					"displayName-count-other": "Australian dollars",
					"symbol": "A$",
					"symbol-alt-narrow": "$"
				},
				"THB": {
					"displayName": "Thai Baht",
					"displayName-count-one": "Thai baht",
					"displayName-count-other": "Thai baht",
					"symbol": "THB",
					"symbol-alt-narrow": "฿"
				},
				"USD": {
					"displayName": "US Dollar",
					"displayName-count-one": "US dollar",
					"displayName-count-other": "US dollars",
					"symbol": "$",
					"symbol-alt-narrow": "$"
				}

I want to print the currency using this format: $23.00 USD. But at the moment I have to add the USD bit myself...

But it comes out looking silly for Thai THB 23.00 THB, or Australian A$23.00 AUD.

It would be good if you had an option to print the currency using the symbol-alt-narrow key instead of the symbol key.

What do you think?

[Proposal] useGlobalize generic type

Hello!

Didn't you think about some way to specify possible list of IDs?
For example:

// it is possible to build programmatically from your translations object, even nested
type AllowedIds = 'guests' | 'yes' | 'no' 

const formatMessage = useGlobalize<AllowedIds>()

formatMessage('yes') // ok
formatMessage('maybe') // compile time error, not runtime

possible generic could be like that (orig code):

export interface Globalize<IDType extends string =string> extends GlobalizeConfig, GlobalizeHelpers, Formatters {
  // ...
  formatMessage(
    id: IDType | IDType[],
    values?: string[] | Record<string, string>,
    options?: MessageFormatterOptions,
  ): string;
  // second overload same way
  // ...

It won't break code for users who don't use this generic (because the fallback is the old type: string).

It won't be useful for users who slash-combined ids: 'party/guests'. But I think than benefit gain worth it, because it makes the lib really type strong (strings are the weak place almost always).
So, for users who prefer to use complex paths (via slash), nothing is changed, meanwhile for users who don't want to rely on strings it would be a huge benefit.

Undefinided is not an object <FormattedCurrency>

I got this error

TypeError: undefinided is not an object (evaluating 'globalize.getCurrencyFormatter')
This error is located at:
in FormmatedCurrency (at withGlobalize.js:16)

This is my short code:
<FormattedCurrency value={9.99} currency="$" numberStyle="code" style={{ color: 'red' }} />

Fallback locale in case formatMessage failure

Hey, thanks for a great library!

Currently I'm in the process of converting our ancient, manual i18n logic to something more streamlined, and I think this library seems like a great fit!

I was wondering though, if it would be possible to set a default locale that would be fallen back to in case formatMessage fails when a local key is missing. In our project, we sometimes make releases before all our translators have translated each new key. In this case we want to fall back to English.

For example, let's say we add a new message, and neglect to translate it to German. If we call formatMessage for that key in DE locale, we don't have a German translation. In this case, I'd like to fall back to English. Only if English key wouldn't exist either, should we fall back to rendering the key itself. Is this possible? I didn't find support for this behavior in your documentation.

getCurrencyFormatter

I receive this error when running the sample code:

Sample Code:

<FormattedCurrency
  value={9.9}
  currency="USD"
  style={{ color: 'red' }} />

Error:

TypeError: Cannot read property 'getCurrencyFormatter' of undefined
    at FormattedCurrency.render (FormattedCurrency.js:25)
    at ReactCompositeComponent.js:793
    at measureLifeCyclePerf (ReactCompositeComponent.js:74)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:792)
    at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:819)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:361)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:257)
    at Object.mountComponent (ReactReconciler.js:47)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:370)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:257)

Is there a compatibility requirement for this library? I'm on React-Native 0.35

FormattedNumber doesn't work with a style

I get an error of "invalid style" when I run this sample for FormattedNumber:

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

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

I've tracked it down to these two lines of code: https://github.com/joshswan/globalize/blob/master/src/number/pattern.js#L14
https://github.com/joshswan/globalize/blob/master/src/number.js#L83

It seems that the style property that is passed in to style the TextField is being passed to the number formatter. Am I doing something wrong? Is there a workaround for this issue?

Cldrjs circular dependency issues PR

I also faced the problem of circular dependency. And as far as I understand you have solved it. Could you create PR with this fixes in upstream?

Npm install warnings with React Native 0.44

When using this package with React Native 0.44 there is a warning about conflicting version numbers for the React package:

npm WARN [email protected] requires a peer of react@>=14.5.0 but none was installed.

This probably has something to do with recent versions of React Native depending on a React 16 alpha version.

typing of `useGlobalize().formatMessage`

Hello!

Thank you very much for the new version with hooks and typings!

There is one obscurity with typing of formatMessage. Typings say that the values object has to contain values of type string or ReactElement:

values?: string[] | Record<string, string>,

values?: Record<string, string | ReactElement>,

But docs provide an example with number:

formatMessage('party/guests', {
  count: 1,
  formattedCount: formatNumber(1),
});

I am not sure which types could be valid for the values values, so I can't provide a good PR. But I could do it, I am just not sure that adding number type is enough.

Thank you.

What format is supported for a cldr json file?

I actually wanted to use INR also along with the default currencies supported by your package. I think i would be able to pass INR as currency to the cldr props of the FormattedWrapper. Can you please share an example of an acceptable json file for the cldr array? Or suggest any other good way of doing it?
Thanks

"Unable to resolve module" - Install issue?

I'm not sure if this is my problem, or something in the dependencies of this project, bit of a JS beginner. I think I have it installed correctly, but the react native packager gives me this error on attempting to load http://localhost:8081/index.ios.bundle

{"message":"Unable to resolve module cldr-data/supplemental/currencyData.json 
from /Users/tfallon/Documents/testproject/node_modules/react-native-globalize/lib/globalize.js: 
Invalid directory /Users/node_modules/cldr-data/supplemental/currencyData.json",
"name":"UnableToResolveError","type":"UnableToResolveError","errors":[{}]}

Seems like something is looking for cldr in some top level node_modules directory, which doesn't exist. I'm running Node 5.4, npm 3.3.12, and the latest React Native. Any idea what could be going wrong here?

Thanks!

formatCurrency always return Error value must be anumber

Hello

I tried to use formatCurrency from useGlobalize

{formatCurrency(product.price, state.currency)
also tried
{formatCurrency(parseInt(product.price), user.currency)

also tried

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

const ExampleComponent = () => (
  <FormattedCurrency value={parseInt(product.price)} currency={user.currency} />
);

all of them retuned same Error !

could you help with this issue ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.