-
Notifications
You must be signed in to change notification settings - Fork 213
/
Copy pathLocalizedRouter.tsx
50 lines (44 loc) · 1.47 KB
/
LocalizedRouter.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
import React from 'react';
import { Router } from 'react-router-dom';
import { IntlProvider } from 'react-intl';
import { Route, Redirect } from 'react-router-dom';
import { messages, AppLanguage, supportedLanguages } from '../intl';
import { routesEnum } from '../Routes';
interface Props {
history: any;
}
export const LocalizedRouter: React.FC<Props> = ({ children, history }) => (
<Router history={history}>
<Route path="/:lang([a-z-]{2,5})">
{({ match, location }) => {
/**
* Get current language
* Set default locale to en if base path is used without a language
*/
const params = match ? match.params : {};
const { lang = AppLanguage.English } = params;
/**
* If language provided is not supported, redirect to "languages" page
*/
if (supportedLanguages.indexOf(lang) < 0) {
return <Redirect push to={routesEnum.languagesPage} />;
}
/**
* If language is not in route path, redirect to language route
*/
const { pathname } = location;
if (!pathname.includes(`/${lang}/`) && pathname !== `/${lang}`) {
return <Redirect to={`/${lang}${pathname}`} />;
}
/**
* Return Intl provider with default language set
*/
return (
<IntlProvider locale={lang} messages={messages[lang]}>
{children}
</IntlProvider>
);
}}
</Route>
</Router>
);