Repository URL to install this package:
|
Version:
4.2.0 ▾
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { IntlProvider } from 'react-intl';
import hash from './hash';
class I18NProvider extends Component {
static propTypes = {
locale: PropTypes.string.isRequired,
messages: PropTypes.object.isRequired,
children: PropTypes.element.isRequired,
};
static generateProviderKey(locale, messages) {
const key = `${locale}${JSON.stringify(messages[locale])}`;
return hash(key);
}
// eslint-disable-next-line class-methods-use-this
shouldComponentUpdate(props) {
const { locale, messages } = props;
return typeof messages[locale] !== 'undefined';
}
render() {
const { locale, messages, children } = this.props;
// Create a hash depending of the current locale and messages object.
// This will enforce the re-render of the provider children when or the locale or only the messages change.
const key = I18NProvider.generateProviderKey(locale, messages);
return (
<IntlProvider key={key} locale={locale} messages={messages[locale]}>
{React.Children.only(children)}
</IntlProvider>
);
}
}
const mapStateToProps = state => ({
locale: state.i18n.locale,
messages: state.i18n.messages,
});
const mapDispatchToProps = () => ({});
export default connect(
mapStateToProps,
mapDispatchToProps
)(I18NProvider);