-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathi18n.component.js
35 lines (31 loc) · 1.07 KB
/
i18n.component.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import React from "react";
export default class I18N extends React.Component {
state = {
currentLanguage: null,
baseUrl: null,
translations: null
};
componentDidMount() {
const languages = ["en", "es"];
const path =
window.location.pathname === "/" &&
window.location.search.startsWith("?p=")
? window.location.search.slice("?p=".length)
: window.location.pathname;
const urlLanguage = languages.find(
language => path.startsWith(`/${language}/`) || path === `/${language}`
);
const navigatorLanguage = window.navigator.language.slice(0, 2);
const languageToUse = urlLanguage || navigatorLanguage || "en";
this.setState({
currentLanguage: languageToUse,
baseUrl: languageToUse === urlLanguage ? `/${languageToUse}` : ""
});
import(/* webpackChunkName: "i18n-" */ `./i18n/${languageToUse}.js`)
.then(mod => mod.default)
.then(translations => this.setState({ translations }));
}
render() {
return this.state.translations ? this.props.children(this.state) : null;
}
}