stefalda / react-localization Goto Github PK
View Code? Open in Web Editor NEWSimple module to localize the React interface using the same syntax used in the ReactNativeLocalization module.
License: MIT License
Simple module to localize the React interface using the same syntax used in the ReactNativeLocalization module.
License: MIT License
Hi there,
Firstly, thanks for this great package. I use it a lot and really enjoy it.
I am having an issue where the .formatString()
method is returning an array as opposed to a string. Do you have any idea what could be causing this?
/i18n/en/validate.js
export default {
lengthMinimum: 'Must be at least {0} characters long.',
};
/i18n/en/index.js
import validate from './validate';
export default { ...validate };
/i18n/index.js
import ReactLocalization from 'react-localization';
import en from './en';
export default new ReactLocalization({
en,
});
/implementation.js
// ...
import i18n from 'i18n';
// ...
export default () => <p>{i18n.formatString(i18n.lengthMinimum, 2)}</p>
I am using version 1.1.0 which gets installed with the "latest" tag even though I do not see it in the list of releases here in GitHub. I have also tried with 1.0.0 and 0.0.18 and get the same result every time.
Hi,
I am getting the following error in ES2015 and v0.1.2:
'react-localization' has no default export
Can you please help?
Not sure if you've ever run into something like this: http://jsbin.com/bejawuqoco/edit?html,js,output
(I couldn't get the actual localization code to run in jsbin, so I just took the expected output from one of the tests.)
The first example is just being rendered inside a div, which seems to work fine. The second one uses the value attribute and ends up adding commas. Do you know of a way to get around this? I'm not actually using it in an input value, that was just so you could visually see the result without using the dom inspector. The real use case is in an aria-label attribute.
I have a slightly hacky fix, so I could submit a pr for review if you don't have an alternative suggestion.
Thanks!
P.S. Awesome module, I really like it so far 😄
import React from "react";
import LocalizedStrings from 'react-localization';
import ReactDOM from "react-dom";
export var language_variant = new LocalizedStrings({
en: {
login_placeholder: "Put your login",
password_placeholder: "Put your password",
button_send: "send"
},
ru: {
login_placeholder: "Введите ваш логин",
password_placeholder: "Введите ваш пароль",
button_send: "Отправить"
},
ua: {
login_placeholder: "Введiть ваш логiн",
password_placeholder: "Введiть ваш пароль",
button_send: "Надiслати"
}
});
getInterfaceLanguage();
getLanguage();
Uncaught ReferenceError: getInterfaceLanguage is not defined
if I try function
import {LocalizedStrings, getLanguage, getInterfaceLanguage} from 'react-localization';
languages.jsx:4Uncaught TypeError: _reactLocalization.LocalizedStrings is not a constructor
Here my localization.js file:
import LocalizedStrings from 'react-localization';
const en = {
...
};
const uk = {
....
};
export const localization = new LocalizedStrings({ en, uk });
export const convertLanguage = function (language) {
switch (language) {
case 'uk':
return { TwoLetter: 'uk', NativeName: 'Українська' };
case 'en':
return { TwoLetter: 'en', NativeName: 'English' };
default:
return { TwoLetter: 'df', NativeName: 'Default' };
}
}
export const extractAvailableLanguages = function (locs) {
return locs.getAvailableLanguages().filter(x => x !== locs.getLanguage());
}
I'm using it in App.js file:
import React, { Component } from 'react';
import MainPage from './MainPage';
import { localization as _l, convertLanguage } from '../localization';
export default class App extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
$('.dropdown-button').dropdown();
}
setLanguage(twoLetter, e) {
e.preventDefault();
_l.setLanguage(twoLetter);
this.forceUpdate();
}
render() {
const currentLanguage = convertLanguage(_l.getLanguage());
return (
<div>
<ul id='languageDropdown' className='dropdown-content'>
{_l.getAvailableLanguages().map(item => convertLanguage(item)).map((item, i) =>
<li key={i}>
<a href='' onClick={this.setLanguage.bind(this, item.TwoLetter)}>
{item.NativeName}
</a>
</li>
)}
</ul>
<nav className='cyan'>
<div className='nav-wrapper'>
<a className='brand-logo' style={{ marginLeft: 16 }}>MyApp</a>
<ul className='right hide-on-med-and-down'>
<li>
<a className='dropdown-button' href='' data-activates='languageDropdown'>
{currentLanguage.NativeName}
<i className='material-icons right'>arrow_drop_down</i>
</a>
</li>
</ul>
</div>
</nav>
<div className='container'>
<MainPage />
</div>
<footer className='page-footer cyan'>
<div className='footer-copyright'>
<div className='container'>
<span style={{ fontWeight: 'normal' }}>© 2017 MyApp</span>
</div>
</div>
</footer>
</div>
)
}
}
Here, I have two problems:
MainPage
doesn't rerendering. How can I rerender all my app, to switch language dynamically?So, how can I solve these problems?
I created a language strings file e.g.:
import LocalizedStrings from 'react-localization';
let strings = new LocalizedStrings({
en:{
how:"How do you want your egg today?",
},
it: {
how:"Come vuoi il tuo uovo oggi?"
}
});
The API works OK if I use the same file
strings.setLanguage('en');
console.log(strings.how);
When I call the API from another file the strings object is empty ({}) and strings.how will return undefined:
import React from 'react';
//the import line:
import strings from '../common/LocalizedStrings';
export default class MyPageNameHere extends React.Component{
constructor (props) {
super(props);
**console.log(strings);
console.log(strings.how);**
}
}
Hope anyone can help.
http://definitelytyped.org/guides/contributing.html
declare module "react-localization" {
interface LocalizedStringsMethods {
setLanguage(language: string): void;
getLanguage(): string;
getInterfaceLanguage(): string;
formatString(str: string, ...values: any[]): string
getAvailableLanguages(): string[]
}
interface LocalizedStringsFactory {
new (props: any): LocalizedStringsMethods;
}
var LocalizedStrings: LocalizedStringsFactory;
export = LocalizedStrings;
}
Hey, so for my code base where I am adding localization, I am thinking of a structure where each component has its string object.
This appears to be slightly more manageable than putting everything down in single big ass file.
Any way to globally set language for all these string instances?
I still get this error:
LocalizedStrings.js:91 Uncaught ReferenceError: interfaceLanguage is not defined(…)
.I see that an issue was opened for it, is it resolved?, for some reason i still see the issue. I'm i missing something?
import LocalizedStrings from 'react-localization';
export let stringTableCons = new LocalizedStrings({
en:{
"Login" : "Login"
},
it: {
Login:"login in italian",
}
});
basically i am exporting stringTableCons to other file and accessing its value by key like "Login", it is working fine but value it changing to uppercase, for my object value is in lower case only but and locally i am not changing it uppercase. please respond.
Thanks
Having a hell of a time trying to get chrome 63 to use a different interface language. I am wondering if anyone else has this issue and if not how do you handle testing these things?
I have set French to be the first priority:
However it stills shows my interface language as en-US
:
strings.getInterfaceLanguage()
"en-US"
I know this isn't related to this package per se so I understand if you want to remove the issue. But if anyone has any insight here it would be greatly appreciated.
Hi ,
formatString is return [object Object] instead of replacing the string in languages.
S.formatString("Value should be between {0} and {1}", 0, 10).
var valueForPlaceholder = valuesForPlaceholders[matchedKey];
here valueForPlaceholder is resolved just fine.
if (!valueForPlaceholder) {
valueForPlaceholder = valuesForPlaceholders[0][matchedKey];
}
here (because of 'if (!0)' is true) it goes undefined.
if (isReactComponent(valueForPlaceholder)) {
here it crashes
Not an issue, just need help with something. I'm having trouble with putting the strings object in a separate file (because i will have lots and lots of text), and import it in the components i need it.
How would the process of changing languages go then? Any help?
Thanks. :)
What is the appetite for supporting named tokens in a new method, to be called like this:
en:{
welcome:"welcome |firstName|, your status is |Status|."
}
...
var tokens = { firstName: "John", status: "Accepted" };
strings.formatStringWithTokens(strings.welcome, tokens);
The benefit of this is that when the strings are handed over to localization teams they have more context of the value in those fields and less room for error.
let strings = new LocalizedStrings({
en:{
dashboard : "{0} dashboard",
}
})
Now using the formatString function and passing to it a JSX element returns [object Object]
strings.formatString(strings.dashboard, <b>Johnny</b>)}
The above line is returning the string
[object Object] dashboard
While the expected result should be
Johnny dashboard
Hello, I'm trying to use this in a TypeScript file but getting this error:
Uncaught TypeError: LocalizedStrings is not a constructor
Here's what my TypeScript file looks like:
import * as LocalizedStrings from "react-localization";
.
.
.
export class EditResponse extends React.Component<{}, IEditResponseState> { constructor(props: any) { super(props);
let strings = new LocalizedStrings({ en: { how: "How do you want your egg today?", boiledEgg: "Boiled egg", softBoiledEgg: "Soft-boiled egg", choice: "How to choose the egg" }, it: { how: "Come vuoi il tuo uovo oggi?", boiledEgg: "Uovo sodo", softBoiledEgg: "Uovo alla coque", choice: "Come scegliere l'uovo" } });
Please help!
Hello, I have two files in this format "filename_locale.js", like:
alert(strings.getLanguage());
const language = strings.getLanguage();
const Projects = require("../assets/projects/Projects_" + language).default;
BUT strings.getLanguage()
always return 'en
' !
navigator is not present in server side. Hence, the function getInterfaceLanguage
throws Reference error.
Any workaround?
I have many strings that would be defined by the user(i.e. dynamically created) and not hard coded, so cannot be stored as json. Not sure I see a way to localize those kind of strings with this approach? Any ideas?
I've implemented something like this in my code. I think it could make it much easier to work when when you can provide multiple translations on the same line:
// Note:
// To make it easier to maintain, I've made the list of strings as a key with
// the two localized strings attached rather than in the default format for 'react-localization'
// which is objects for each language containing key value pairs.
type Strings_EN_FI = {
[string]: Array<string>
};
type Object_EN_FI = {
en: Object,
fi: Object
};
const remapStrings = (strings: Strings_EN_FI): Object_EN_FI => {
let en = {};
let fi = {};
Object.keys(strings).map(key => {
const [enValue, fiValue] = strings[key];
en[key] = enValue;
fi[key] = fiValue;
});
return { en, fi };
};
Hello,
It seems that formatString isn't working. When i'm trying to replace '{0}' with juste a simple string, my navigator is displaying '{0}'
localization.js
const strings = new LocalizedStrings({
FR,
EN
});
strings.formatString(strings.search.placeholder, 'test')
export default strings
en.js (same as fr.js)
export default {
search: {
placeholder: 'test {0}',
},
}
Is there a solution ?
Not an issue, but need more clarification on an api.
I tried running an example using the formatString() and resulted:
tests are {0} configurable to your liking.Select from all tests {1}, to customize your own.
here is the json:
{
"title": "title.",
"test": "Start your first test",
"description": "tests are {0} configurable to your liking.Select from all tests {1}, to customize your own."
}
what im doing wrong?
For purposes of testing React components that use strings from react-localization, I would like to be able set the content of LocalizedStrings
instance with strings identifying each key's language-independent keypath. For example, suppose I have:
var strings = new LocalizedStrings({
en: {
a: {
b: { x: "foo", y: "bar" },
c: { z: "baz" }
}
}
});
I would like to be able to set the content of strings
with:
const contentForTesting = {
en: {
a: {
b: { x: "a.b.x", y: "a.b.y" },
c: { z: "a.c.z" }
}
}
};
In react-localization v0.0.15
, I could accomplish this as follows:
strings.props = contentForTesting;
strings.setLanguage(strings.getLanguage()); // Resets LocalizedStrings object with new props
In react-localization v0.0.16
, this no longer works with the introduction of setContent()
.
Expected behavior:
strings.setContent(contentForTesting)
maintains en
as current language and successfully replaces the content of strings
.
Observed behavior:
strings.setContent(contentForTesting)
throws an error because "a"
is a reserved keyword.
Hey,
I am new to Typescript, but having problems using the code from the second comment: Issue 42
There is some error in LocalizedStrings.d.ts:
`export type LocalizedStrings = LocalizedStringsMethods & T;
interface LocalizedStringsFactory {
new <T>(props: GlobalStrings<T>): LocalizedStrings<T>;
}
var LocalizedStrings**Factory**: LocalizedStringsFactory;
export default LocalizedStrings**Factory**;`
The LocalizedStrings should be renamed to LocalizedStringsFactory, otherwise we cannot use both (type and var) at the same time.
My own code:
`
// strings.ts
import { enStrings } from "./en";
import { deStrings } from "./de";
import LocalizedStringsFactory, {LocalizedStrings} from "react-localization";
export interface LocaleStrings {
key1: string;
key2: string;
}
export const strings: LocalizedStrings = new LocalizedStringsFactory({
en: enStrings,
de: deStrings
});
`
I was wondering why my application wouldn't work on my android phone's built in browser, and found out here's the problem. You are checking for languages with this:
let interfaceLanguage = navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage || 'en-US');
If it finds an "undefined" value, it will return it, which will cause the following error in _getBestMatchingLanguage:
Uncaught TypeError: Cannot read property 'indexOf' of undefined
Replacing the line with this fixes the issue:
let interfaceLanguage = (navigator.languages && typeof navigator.languages !== 'undefined' && navigator.languages[0] && typeof navigator.languages[0] !== 'undefined') ? navigator.languages[0] : ((navigator.language && typeof navigator.language !== 'undefined') ? navigator.language : ((navigator.userLanguage && typeof navigator.userLanguage !== 'undefined') ? navigator.userLanguage : 'en-US'));
getInterfaceLanguage throws error cause there is a typo
add this function
{
key: 'setContent',
value: function setContent(props) {
this.props=props;
}
},
then its possible at runtime rewrite texts (example loaded from server)
locale.setContent({sv:myNewContent});
locale.setLanguage("sv")
Maybe it is a good option to react-localization returns searched key when does not found, instead of null. This helps to identify missed translations.
Chrome version: 59.0.3071.115
When I have selected other language than English for example Finnish because I am from Finland after all :D
It still choose English as my language inside of _getInterfaceLanguage
despite my language was set to Finnish.
I debugged _getInterfaceLanguage
and the logic always goes to first branch of the if statement which chooses language from navigator.languages[0]
But as you can see from this image the finnish language is last item in the array
I think possible solution would be to move second if statement branch as first so it would first check if navigator.language
would exist and use that. After that it would use navigator.languages[0]
Also according to this all browsers should have navigator.language
so it should be priority
Source: detect-browser-language-in-javascript
I keep getting this error
🚧 👷 key '0' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '1' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '2' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '3' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '4' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '5' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '6' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '7' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '8' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '9' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '10' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '11' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '12' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '13' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '14' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '15' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '16' not found in localizedStrings for language id 🚧
index.5a32104….js:151236 🚧 👷 key '17' not found in localizedStrings for language id 🚧
I'm trying to use the same strings in the backend as well to render some stuff in the page markup, like prerender the <title></title>
tag before react app is loaded
I have main page component, and child component, that is used inside it. On language switch, changes are reflected only in main component, not in child. Any ideas why it's like that? On page reload, language is changed in both components though.
Not an issue, but does this lib have support for date formatting?
The error says: Uncaught (in promise) TypeError: Cannot read property 'indexOf' of null in LocalizedStrings:js:56.
After I reload the page, and continue using the page normally, the error doesn't occur at all.
let strings = new LocalizedStrings({
en:{
how:"How do you want your egg today?",
boiledEgg:"Boiled egg",
softBoiledEgg:"Soft-boiled egg",
choice:"How to choose the egg"
},
it: {
how:"Come vuoi il tuo uovo oggi?",
boiledEgg:"Uovo sodo",
softBoiledEgg:"Uovo alla coque",
choice:"Come scegliere l'uovo"
}
});
This line gives error cannot read property indexOf of undefined.
Problem I'm trying to solve: Add some localization for differences between UK and US readers.
Roadblock: Can't tell what language codes you use.
Solution: Could you add a link to what reference you're using?
I have an english and french website. I would like first detected value to be used if 'english' is not found
let strings = new LocalizedStrings({
en: {
signinTitle: 'Sign in',
},
fr: {
signinTitle: 'Connexion',
signoutTitle: 'Déconnexion', // <-- use this value if 'signoutTitle' is not defined in english
}
});
It could also be to add a 'default' key
let strings = new LocalizedStrings({
default: {
signoutTitle: 'test' // <-- English is my default language browser but not defined in 'en', so use the 'default' key value
}
en: {
signinTitle: 'Sign in',
},
fr: {
signinTitle: 'Connexion',
signoutTitle: 'Déconnexion',
}
});
How do I integrate the script so that I only have one instance and all placeholders are replaced if i call setLanguage()?
hi,
i need to keep localize file as common,and use globally.how can i acheive the same?
Why does it not return a formatted string instead? Or is there something I'm not doing right?
Thanks
If I (1) place a JSX.Element instead of a string for a language item and (2) the browser language is set to the second language of the dictionary (here en), the React app is unable to start. If the language is set to the first language specified in the dictionary, the JSX.Element is succesfully shown.
key 'gutterBottom' not found in localizedStrings for language en
key 'noWrap' not found in localizedStrings for language en
key 'paragraph' not found in localizedStrings for language en
Uncaught TypeError: Cannot assign to read only property key of object '#Object''
The problematic code:
de: {
helloWorld: <Typography style={styles.fontStyleText}>
Hallo <i>Welt</i>
</Typography>,
},
en: {
helloWorld: <Typography style={styles.fontStyleText}>
Hello <i>World</i>
</Typography>,
}
If I change this line to simple string App is able to start:
en: {
helloWorld: 'Hello <i>World</i>'
},
If you define a word for "language", the getLanguage() function will return the localized string for the key "language". Presumably this would happen if you used a key called "getLanguage" or any other internal name as well.
Expected:
It should warn you whenever you try to define a reserved word.
Hi there, I am not sure if this is issue for you or just me doing something wrong. Maby you could hep me anyway :P
I am working with typescript.
import LocalizedStrings from "react-localization";
export const strings = new LocalizedStrings({
en: {
ImageDescription: "Here choose your logo that will be displayed on index page",
},
sk: {
ImageDescription: "Here choose your logo that will be displayed on index page",
},
});
const myReource = strings.ImageDescription;
on the last line i get error ts error:
[ts] Property 'ImageDescription does not exist on type 'LocalizedStringsMethods'.
But as i seen your d.ts file it seems like logic bug.
Thx for respond.
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.