joshswan / react-native-globalize Goto Github PK
View Code? Open in Web Editor NEWInternationalization (i18n) for React Native
License: MIT License
Internationalization (i18n) for React Native
License: MIT License
Trying to use useGrouping on FormattedNumber has no effect at all.
I'm using the following code:
<FormattedNumber
value={2500.5}
mininumFractionDigits={2}
maximumFractionDigits={2}
useGrouping={true}
/>
The output is get is
2500.5
when in fact I expect
2,500.50
I'm getting the following error " Cannot read property 'getPluralGenerator' of undefined"
<FormattedPlural
value={0}
zero={<Text>Photo(</Text>}
other={<Text>Photos</Text>} />
Is there a way to customize which locales and currency I wanna support?
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.
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 ?
Hi,
Is it possible to add a prefix to FormattedNumber or FormattedCurrency?
I need to add an "%" to the number.
Thanks
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?
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
:
react-native-globalize/src/globalize/types.ts
Line 136 in f27ba15
react-native-globalize/src/globalize/types.ts
Line 141 in f27ba15
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.
Reproducible demo repo:
Expo React native project.
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
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?
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!
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
react native packager works great on es6+ code, there is no need to transpile it
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?
Thank you for this great library. It would be helpful for our automating testing if the Components in this library accepted and used an accessibilityLabel
prop.
pt-BR is missing
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!
I'm receiving the following error when I try to format a date
<FormattedDate
value={new Date()}
skeleton="dMy"
/>
skeleton="yMd"
works fine
Hi, i use FormattedWrapper to support multi language,However, normal language can be acquired only in subcomponents.How do I get language from a non child component?Thanks
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 locale
en_TW.'
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
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".
How to resolve this?
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)
Is there's a way to do localization programatically without using <FormattedMessage />
?
My use case is that I receive a key and need to get a message based on it but my function is outside of React, therefore I don't have access to context
.
I can use the Globalize class but I would have to go through all the algorithm to format it. Perhaps it's a good option to export that algorithm as well.
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).
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?
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:
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;
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?
moment/moment error
moment/moment#4187 (comment)
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
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...
messages: {
"hello": "Hey"
}
<FormattedMessage message="hello" />
//HEY
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
Can you give me an example? Thanks~~
Getting this error:
Cannot read property 'getCurrencyFormatter' of undefined
FormattedCurrency.render
FormattedCurrency.js:25:50
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' }} />
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.
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') {
Hi, how to add Locales & Currencies? I want to add Currency of my country.
Thanks.
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.
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
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 ?
Is it possible to get only the string without use FormattedMessage ?
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.
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.
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
It would be helpful to be able to turn off the allowFontScaling property for each of the Text controls in this library.
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
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.