-
Notifications
You must be signed in to change notification settings - Fork 0
/
LocalizedRoute.tsx
85 lines (74 loc) · 2.22 KB
/
LocalizedRoute.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
/*eslint no-redeclare: "off" */
import { History as IHistory } from 'history';
import * as React from 'react';
import {
Route, RouteComponentProps as IRouteComponentProps, RouteProps as IRouteProps
} from 'react-router-dom';
import { getLocalizedPath, getLocalizedRoute } from './localizer';
import { Translator } from './Translator';
interface IProps extends IRouteProps {
localize?: boolean; // * default true
children?: any; // ! Patch to eliminate TypeScript false positive error: no call signature on children
}
/**
* A custom intercepted Route component
* Docs: https://github.com/ReactTraining/react-router/blob/59a4fbc184f3a3cf4c25ee39a7e97f72efed7849/packages/react-router/modules/Route.js#L112-L116
* @param props
*/
const LocalizedRoute: React.FunctionComponent<IProps | any> = (props) => {
const { children, component: Component, localize = true, render, exact, path, ...rest } = props;
const interceptHistory = (history: IHistory, language: string) => {
const push = (pushedUrl: string) => {
const localizedUrl: string = getLocalizedRoute(language, pushedUrl);
history.push(localizedUrl);
};
return {
...history,
push,
};
};
const interceptProps = (routeComponentProps: IRouteComponentProps | any, language: string) => {
return {
...routeComponentProps,
history: interceptHistory(routeComponentProps.history, language),
};
};
const getInterceptedPath = (): string | string[] | undefined => {
if (path && localize) {
return getLocalizedPath(path);
}
if (path) {
return path;
}
return undefined;
};
return (
<Translator
render={(language: string) => {
return (
<Route
path={getInterceptedPath()}
exact={exact}
history={history}
render={(renderRouteProps: IRouteComponentProps) => {
if (Component) {
return (
<Component {...interceptProps(renderRouteProps, language)} />
);
}
if (render) {
return render(interceptProps(renderRouteProps, language));
}
if (typeof children === 'function') {
return children(renderRouteProps);
}
return null;
}}
{...rest}
/>
);
}}
/>
);
};
export { LocalizedRoute, IProps as ILocalizedRouteProps };