In the app main file we will add the <IntlProvider />
component wrap the whole app.
and add the locale data for any language we need to add.
you can choose any language available inside the locale-data
folder inside the module.
file: src/client/app.js
import { IntlProvider, addLocaleData } from 'react-intl';
import arLocaleData from 'react-intl/locale-data/ar';
// here we the translations as an object containing each language translation
import i18n from './i18n';
// call addLocaleData globally
addLocaleData(arLocaleData);
export default class App extends React.Component {
componentWillMount() {
this.setState({ locale: 'en' });
}
handleLocaleChange(locale, e) {
this.setState({ locale });
}
render() {
const messages = i18n[this.state.locale];
return (
<IntlProvider locale={this.state.locale} key={this.state.locale} messages={messages}>
<div>
<div
className="hidden-print lang-select"
style={{
position: 'fixed',
zIndex: 1,
top: '50%',
left: this.state.locale === 'ar' ? '15px' : '',
right: this.state.locale === 'ar' ? '' : '15px'
}}>
<img
onClick={this.handleLocaleChange.bind(this, 'en')}
src={require('../assets/images/flags/gb.svg')}
alt={messages['locale.en']}
title={messages['locale.en']}
style={{ width: 32, height: 32, display: 'block', cursor: 'pointer' }}
/>
<img
onClick={this.handleLocaleChange.bind(this, 'ar')}
src={require('../assets/images/flags/ae.svg')}
alt={messages['locale.ar']}
title={messages['locale.ar']}
style={{ width: 32, height: 32, display: 'block', cursor: 'pointer', marginTop: 10 }}
/>
</div>
<DummyApp />
</div>
</IntlProvider>
);
}
}
So in the App
Component above We just surround the component <DummyApp />
by the IntlProvider
and added the language selector which change the component state with the required language.
And then we load the correct translation from the translation object based on current selected language and pass it to the IntlProvider
const messages = i18n[this.state.locale];
Once you have that setup you can use translations inside any child component inside our <DummyApp />
You just have to surround that component with a HOC - Higher Order Component - called injectIntl()
Example :
import React from 'react';
import { injectIntl } from 'react-intl';
import home from './home-md'
class Home extends React.Component {
render() {
// those props are added automatically because the component is wrapped by injectIntl
const { locale, messages } = this.props.intl;
return (
<div>
{messages['hello.world']} <br />
Current Locale is {locale}
<div dangerouslySetInnerHTML={{ __html: home[locale] }} />
</div>
);
}
}
export default injectIntl(Home);
So you can use the locale
variable in any way you want to load the correct .md files per language for example.
It's up to you as a coder how to handle loading translations.