How to implement localization in reactjs?
Asked Answered
R

4

23

We need to implement the localization in reactjs to define the string value(s). How can I implement that?

One link is there https://www.npmjs.com/package/react-localization, but I am not getting the correct steps to add that.

I have tried by following steps:

  1. I am adding my component in ES6:
    class Home extends React.Component
    {
        constructor(props) {
            super(props);
        }
        render() {
            return (
              <Text>{strings.how}</Text>
             );
        }
    }

  1. I have added the localization code as:-
    import LocalizedStrings from 'react-localization';
    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"
        }
    });

Now if you will see above :- {strings.how} I should able to get the strings value as it is defined in localization but I am not able to do it.

Roasting answered 22/11, 2016 at 12:21 Comment(1)
I would suggest you change the accepted answer since the current one links to a completely different package.Precincts
L
32

npm install react-localization

import ReactDOM from 'react-dom';
import React, { Component } from 'react';
import LocalizedStrings from 'react-localization';

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

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      language: 'en'
    }
    
    this.handleLanguageChange = this.handleLanguageChange.bind(this);
  }

  handleLanguageChange(e) {
    e.preventDefault();
    let lang = e.target.value;
    this.setState(prevState => ({
      language: lang
    }))
  }

  render() {
    strings.setLanguage(this.state.language);
    return (
      <div>
        Change Language: <select onChange={this.handleLanguageChange}>
          <option value="en">En- English</option>
          <option value="it">It- Italian</option>
        </select>
        <br /><br />
        {strings.how}
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

u can put your language specific data in a JSON file or or .js file. call that file in your current file and pass that object to new LocalizedStrings().

Example: data.js

const data = {
  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"
  }
}
export {data};

in your current file import it as import { data } from './data.js'; and then you can initialise as let strings = new LocalizedStrings({data});

You can read the detailed article here - react-localization with hooks

Check the working demo Here

Lordinwaiting answered 17/4, 2019 at 8:55 Comment(5)
is this calling strings.setLanguage(this.state.language) on the render function necessary ?Avram
@Avram yes, it is necessaryLordinwaiting
Thanks didn't see any examples or explanation of this on the docs ( readme file)Avram
What if you want to use html tags inside messages? Example: "<strong>Goodby> dear user"Firearm
this code can work only on one file...you cannot update language in one file and access to somewhere elseVillainy
S
17

Yahoo has created a package for implementing localization in React that might be what you are looking for: https://github.com/yahoo/react-intl. It takes care of "dates, numbers, and strings, including pluralization and handling translations".

Update 2021: Here's the package now days:

Spawn answered 22/11, 2016 at 12:24 Comment(6)
react-localization didn't seem to exist when I wrote my answer almost 3 years ago so I don't really see any point for downvoting this? Jees..Spawn
FYI: Keep downvoting this answer won't make it go away since SO shows the accepted answer at the top, @Gorakh Nath needs to change the accepted answer.Spawn
wait, how the heck did react-localization didn't exist at the time but the OP managed to mention it in the question itself? lolPrecincts
btw, even the link is broken nowadays - it goes to some other package named format.jsPrecincts
The link works, it goes to the monorepo where react-intl lives. It's just a different organization now. The package was updated yesterday and has almost 1 million weekly downloads and 12k stats on GH. react-localization hasn't been updated in 2 years, has 36k weekly downloads and just 300 stars. But you do you.Spawn
Yeah react-localization existed in a 0.0.1 version. I just looked at the other answer (not the question) and somehow missed that Published on npm is when it was last updated and not first published. Life goes on.Spawn
P
4

We use react-i18next. And then use i18nexus to auto-translate and manage translations.

Penny answered 13/6, 2020 at 17:27 Comment(1)
I've used react-i18next and it seems like a pretty robust solution to providing localization on the front-end. It also seems to be well maintained as it seems to be updated pretty often and has a large number of weekly downloads on npm.Elamite
M
0

first Add the dependencies

npm install --save react-i18next i18next

If you are following along, start the app with npm start so you can give the two pages a look.

Create the file structure In the src folder, create an i18n folder to hold all the information related to translating the app. Here’s the structure I used that is pretty common:

src
+-- i18n
    +-- locales
    |    +-- en
    |        +-- translations.json
    |    +-- es
    |        +-- translations.json
    +-- config.js

The config.js file contains the set up for the i18n instance. The two JSON files will hold the text that goes in the app. en for English and es for Spanish. If you are following along, create the file structure in the boilerplate.

Configure the i18n instance The i18n instance will hold all of your translations, the current language, and other info and methods needed. You can configure it in the config.js file like this:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

i18n.use(initReactI18next).init({
  fallbackLng: 'en',
  lng: 'en',
  resources: {
    en: {
      translations: require('./locales/en/translations.json')
    },
    es: {
      translations: require('./locales/es/translations.json')
    }
  },
  ns: ['translations'],
  defaultNS: 'translations'
});

i18n.languages = ['en', 'es'];

export default i18n;

At the top, import the necessary dependencies. Next, the use(initReactI18next) will bind react-i18next to the i18n instance.

The first two properties of the init object parameter are a fallback language (fallbackLng) and default language (lng). I set both of these to English (en).

The resources are the JSON files with the translations that you created in the last step. The namespaces (ns) and default namespace (defaultNS) are the keys from the resources object.

You can split your translations into multiple files (namespaces) if you have a large app to simplify the files. In which case, you would add more than just the one file in the resources object and add it to the namespaces array. This app is small, so all the translations can go in one file.

Add the i18n instance to your app In the index.js file of the boilerplate, which contains the entire app, import the i18n instance you created like this:

import './i18n/config';

Next, add an empty object {} to your two translations.json files so you don’t get any errors. You will fill in the keys later.

Translate a functional component with the useTranslation hook The Nav.js file is the first component to translate. It’s a functional component, so you can use the useTranslation hook. Import it at the top with import { useTranslation } from 'react-i18next'.

Next, instead of using the implicit return with the component, add curly brackets and the return statement so you can declare a variable. Get the t function from the hook with const { t } = useTranslation();.

All together, it should look like something this:

import { useTranslation } from 'react-i18next';

const Nav = () => {
  const { t } = useTranslation();

  return (
    …
  );
}

The text you want to translate in this component is Home and Page 2. In your English translations.json file, add two properties to the object:

{
  "home": "Home",
  "page2": "Page 2"
}

Now, you can pass those keys to the t function to get the text. In the Nav.js component, use the t function to translate Home and Page 2 to the English text like this: t('key-from-json-file').

Here’s how those lines should look:

import { useTranslation } from ‘react-i18next;

const Nav = () => {
  const { t } = useTranslation();

  return (
    …

    <Link to="/">{t('home')}</Link>
    <Link to="/page2">{t('page2')}</Link>
  );
}

Preview in Spanish The two nav buttons should be working for English. Add the same two keys to the Spanish JSON file so you can see what it will look like in Spanish. Here’s the translations:

{
  "home": "Casa",
  "page2": "Página 2"
}

After that, go to the config.js file, set the lng (default language) to es and reload the page. The nav links should show up in Spanish. When you are done, you can set the default language back to en.

change languages with tab

All the desired text should be available in both English and Spanish now. The last thing to do is to make it easy to switch between languages.

The Footer.js file has a few buttons and a changeLanguage function. Import the useTranslation hook from react-i18next at the top of the file. At the top of the Footer component, get the i18n instance from it like this: const { i18n } = useTranslation();.

Finally, in the changeLanguage function, use the i18n.changeLanguage() method, passing e.target.value to it, to change the langauge.

All together, it looks like this:

import { useTranslation } from 'react-i18next';

const Footer = () => {
  const { i18n } = useTranslation();

  function changeLanguage(e) {
    i18n.changeLanguage(e.target.value);
  }

  return(
    <div className='footer'>
      <button onClick={changeLanguage} value='en'>English</button>
      <button onClick={changeLanguage} value='es'>Español</button>
    </div>
  )
}

Now, you should be able to switch languages by clicking the buttons on each page.

I found this article here. :LINK:

Mahratta answered 14/10, 2022 at 1:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.