Git Product home page Git Product logo

react-localization's People

Contributors

aaronrobson avatar aykutkardas avatar bfcoder avatar callmemagnus avatar ceyhun avatar dependabot[bot] avatar domino987 avatar elitemastereric avatar fernandosouza avatar goodhyun avatar henrikra avatar jonanderdev avatar joshsalverda avatar kaspergreen avatar nightblade9 avatar saadahmadhere avatar shahankit avatar stanleygoldman avatar stefalda avatar

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  avatar

react-localization's Issues

.formatString returning array

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.

Using string.Format inside of an attribute adds commas

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 😄

doesn't work getInterfaceLanguage(); getLanguage(); ReferenceError: getInterfaceLanguage is not defined

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

Problem with switching to english language

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:

  1. Switching to ukrainian language works good, but child components in MainPage doesn't rerendering. How can I rerender all my app, to switch language dynamically?
  2. When I'm switching to english language, nothing happens. It seems like it happens only with english language, because with other languages it works pretty fine.

So, how can I solve these problems?

import strings to anther class

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.

Add typescript definitions (d.ts)

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;
}

Globally Force Locale

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?

Still get the error, interfaceLanguage undefined

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?

value is chaning to uppercase

My code is like this

import LocalizedStrings from 'react-localization';

export let stringTableCons = new LocalizedStrings({
en:{
"Login" : "Login"
},
it: {
Login:"login in italian",
}
});

export default stringTableCons;
stringTableCons.setLanguage('it');

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

Testing languages in Chrome

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:

screen shot 2018-01-02 at 9 13 48 am

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.

formatString not working with falsy values as parameter

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

Define strings in a separate file

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. :)

Support for named tokens for format string

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.

formatString - Replacing string with a JSX element return [object Object]

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

Use with TypeScript

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!

getLanguage() always return 'en'

Hello, I have two files in this format "filename_locale.js", like:

  • Projects_en.js
  • Projects_fa.js
    I check language at begining and import right file like this:
alert(strings.getLanguage());
const language = strings.getLanguage();
const Projects = require("../assets/projects/Projects_" + language).default;

BUT strings.getLanguage() always return 'en' !

Localize a dynamically created text

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?

Feature: make an option to initialize based on an object with the format { hello: ["hello", "bonjour", "guten tag"] }

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  };
};

formatString isn't working

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 ?

How does the formatString work?

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?

In v0.0.16, setContent throws reserved keyword error when trying to replace content of existing keypaths

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.

Typescript export LocalizedStrings

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
});
`

Not checking for undefined in interfaceLanguage

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'));

Runtime change content

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")

Return key when not found

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.

[BUG] Wrong language is chosen on Chrome

Problem description

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
image

Possible solution

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
image
Source: detect-browser-language-in-javascript

Apply Flowtype for react-localization

Hi guys

We working applied both react-localization and flow type in our project. But we faced some error between flow-type. Please check below

So is react-localization supported flow-type yet?
screen shot 2017-11-23 at 10 27 32 am

Key not found for language

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 🚧

Language is not changed in child component on switch language

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 working with React Native

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.

Localization Keys Link

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?

Default Value if no language is found?

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',
  }
});

JSX.Element causes app crash at start: Uncaught TypeError: Cannot assign to read only property key of object '#Object''

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>'
},

Setting reserved words like "language" doesn't throw any warnings.

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.

How exactly typescript compile code?

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.

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.