i18n module extension for React applications that provides several components (tags) for rendering i18n messages.
Everything is stored in i18n (I18nManager instance) object in scope of React context.
React application should initialize i18n object and propagate it for child components.
/**
* App
*/
class App extends React.Component {
static propTypes = {
locale: React.PropTypes.string.isRequired
};
static childContextTypes = {
i18n: React.PropTypes.object.isRequired
};
getChildContext() {
return {
i18n: new I18nManager(this.props.locale)
};
}
render() {
return (
<div>
<MyComponent />
</div>
);
}
}
export default function(element, props) {
return React.render(<App {...props} locale="en-US" />, element);
};
Each component may register own messages in global i18n using register method of I18nManager.
/**
* Root element of custom component.
*/
class MyComponent extends React.Component {
static contextTypes = {
i18n: React.PropTypes.object.isRequired
};
static childContextTypes = {
i18n: React.PropTypes.object.isRequired
};
getChildContext() {
const translations = [{
locales : ['en-US'],
messages: {
logo: {
title: 'Title',
text: 'Text'
}
}
}];
return {
i18n: this.context.i18n.register('MyComponent', translations)
};
}
render() {
return (
<header className="header-style">
<a href="#" className="logo-style" title={this.context.i18n.getMessage('logo.title')}>
<FormattedMessage message="logo.text" />
</a>
</header>
);
}
}
npm run lint
npm test
npm start