How to implement localization in reactjs?
We use react-i18next. And then use i18nexus to auto-translate and manage translations.
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:
- https://github.com/formatjs/formatjs
- https://www.npmjs.com/package/react-intl
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