-
Notifications
You must be signed in to change notification settings - Fork 228
/
react-i18next.js
58 lines (48 loc) · 1.78 KB
/
react-i18next.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const React = require('react');
const reactI18next = require('react-i18next');
const hasChildren = (node) => node && (node.children || (node.props && node.props.children));
const getChildren = (node) => (node && node.children ? node.children : node.props && node.props.children);
const renderNodes = (reactNodes) => {
if (typeof reactNodes === 'string') {
return reactNodes;
}
return Object.keys(reactNodes).map((key, i) => {
const child = reactNodes[key];
const isElement = React.isValidElement(child);
if (typeof child === 'string') {
return child;
}
if (hasChildren(child)) {
const inner = renderNodes(getChildren(child));
return React.cloneElement(child, { ...child.props, key: i }, inner);
}
if (typeof child === 'object' && !isElement) {
return Object.keys(child).reduce((str, childKey) => `${str}${child[childKey]}`, '');
}
return child;
});
};
const useMock = [(k) => k, {}];
useMock.t = (key, defaultValue, options = {}) => {
let translatedString = defaultValue;
Object.keys(options).forEach((key) => {
if (key != 'interpolation') {
translatedString = defaultValue.replace(`{{${key}}}`, `${options[key]}`);
}
});
return translatedString ?? key;
};
useMock.i18n = {};
module.exports = {
// this mock makes sure any components using the translate HoC receive the t function as a prop
Trans: ({ children }) => renderNodes(children),
Translation: ({ children }) => children((k) => k, { i18n: {} }),
useTranslation: () => useMock,
// mock if needed
I18nextProvider: reactI18next.I18nextProvider,
initReactI18next: reactI18next.initReactI18next,
setDefaults: reactI18next.setDefaults,
getDefaults: reactI18next.getDefaults,
setI18n: reactI18next.setI18n,
getI18n: reactI18next.getI18n,
};