-
Notifications
You must be signed in to change notification settings - Fork 154
/
index.tsx
115 lines (100 loc) · 2.81 KB
/
index.tsx
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import React from 'react';
import intl from 'core/intl';
import useForceUpdate from 'use-force-update';
import enUS from 'locales/en-US.json';
import zhCN from 'locales/zh-CN.json';
import zhTW from 'locales/zh-TW.json';
import frFr from 'locales/fr-FR.json';
import jaJP from 'locales/ja-JP.json';
import BasicComponent from 'components/basic';
import PluralComponent from "components/plural";
import HtmlComponent from "components/html";
import DateComponent from "components/date";
import CurrencyComponent from "components/currency";
import MessageNotInComponent from "components/message-not-in-component";
const LOCALES_LIST = [
{
label: "English",
value: "en-US",
},
{
label: "简体中文",
value: "zh-CN",
},
{
label: "繁體中文",
value: "zh-TW"
},
{
label: "français",
value: "fr-FR"
},
{
label: "日本語",
value: "ja-JP"
}
];
const LOCALE_DATA = {
"en-US": enUS,
"zh-CN": zhCN,
"zh-TW": zhTW,
"fr-FR": frFr,
"ja-JP": jaJP,
}
const ReactIntlUniversalExample: React.FC<any> = (props) => {
const forceUpdate = useForceUpdate();
const [initDone, setInitDone] = React.useState(false);
React.useEffect(() => {
initializeIntl();
}, []);
const initializeIntl = () => {
// 1. Get the currentLocale from url, cookie, or browser setting
let currentLocale = intl.determineLocale({
urlLocaleKey: 'lang', // Example: https://fe-tool.com/react-intl-universal?lang=en-US
cookieLocaleKey: 'lang', // Example: "lang=en-US" in cookie
});
// 2. Fallback to "en-US" if the currentLocale isn't supported in LOCALES_LIST
if (!LOCALES_LIST.some(item => item.value === currentLocale)) {
currentLocale = "en-US"
}
// 3. Set currentLocale and load locale data
setCurrentLocale(currentLocale);
// 4. After loading locale data, start to render
setInitDone(true);
}
const setCurrentLocale = (currentLocale: string) => {
intl.init({
// debug: true,
currentLocale,
locales: LOCALE_DATA,
});
};
const onLocaleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
setCurrentLocale(e.target.value);
forceUpdate();
}
const localeSelector = (
<select onChange={onLocaleChange} defaultValue="">
<option value="" disabled>Change Language</option>
{LOCALES_LIST.map(locale => (
<option key={locale.value} value={locale.value}>{locale.label}</option>
))}
</select>
);
return (
<div>
{initDone && (
<div className="react-intl-universal-example">
{localeSelector}
<BasicComponent />
<PluralComponent />
<HtmlComponent />
<DateComponent />
<CurrencyComponent />
<MessageNotInComponent />
</div>
)}
</div>
);
}
export default ReactIntlUniversalExample;