Skip to content

Instantly share code, notes, and snippets.

@JoaoCnh
Created February 5, 2018 15:31
Show Gist options
  • Save JoaoCnh/446d4678f68d80bd45c73c6f8fe85aaa to your computer and use it in GitHub Desktop.
Save JoaoCnh/446d4678f68d80bd45c73c6f8fe85aaa to your computer and use it in GitHub Desktop.
Localization Provider
import React, { Component } from "react";
import PropTypes from "prop-types";
import Polyglot from "node-polyglot";
// for example
import translations from "../my-translations.json";
class I18nProvider extends Component {
static propTypes = {
locale: PropTypes.string.isRequired,
children: PropTypes.node.isRequired
};
static contextTypes = {
t: PropTypes.func,
locale: PropTypes.string
};
static childContextTypes = {
t: PropTypes.func.isRequired,
locale: PropTypes.string.isRequired
};
getChildContext() {
const { locale } = this.props;
const polyglot = new Polyglot({
locale: locale,
phrases: translations,
});
const t = polyglot.t.bind(polyglot);
return { t, locale };
}
render() {
const { children } = this.props;
return React.Children.only(children);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment