/
withTranslation.js
35 lines (29 loc) · 1.17 KB
/
withTranslation.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 { createElement, forwardRef as forwardRefReact } from 'react';
import { useTranslation } from './useTranslation';
import { getDisplayName } from './utils';
export function withTranslation(ns, options = {}) {
return function Extend(WrappedComponent) {
function I18nextWithTranslation({ forwardedRef, ...rest }) {
const [t, i18n, ready] = useTranslation(ns, { ...rest, keyPrefix: options.keyPrefix });
const passDownProps = {
...rest,
t,
i18n,
tReady: ready,
};
if (options.withRef && forwardedRef) {
passDownProps.ref = forwardedRef;
} else if (!options.withRef && forwardedRef) {
passDownProps.forwardedRef = forwardedRef;
}
return createElement(WrappedComponent, passDownProps);
}
I18nextWithTranslation.displayName = `withI18nextTranslation(${getDisplayName(
WrappedComponent,
)})`;
I18nextWithTranslation.WrappedComponent = WrappedComponent;
const forwardRef = (props, ref) =>
createElement(I18nextWithTranslation, Object.assign({}, props, { forwardedRef: ref }));
return options.withRef ? forwardRefReact(forwardRef) : I18nextWithTranslation;
};
}