-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathLocaleProvider.jsx
More file actions
43 lines (35 loc) · 1.07 KB
/
LocaleProvider.jsx
File metadata and controls
43 lines (35 loc) · 1.07 KB
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
import { IntlProvider } from 'react-intl';
import { defaultLocale } from '../site.json' with { type: 'json' };
const LOCALE_COOKIE = 'NEXT_LOCALE';
/**
* Detects the locale from the cookie.
* Falls back to the default locale when the cookie is missing.
*
* @returns {string}
*/
export const detectLocaleFromCookies = () => {
if (typeof document === 'undefined') {
return defaultLocale;
}
const localeCookie = document.cookie
.split(';')
.map(cookie => cookie.trim())
.find(cookie => cookie.startsWith(`${LOCALE_COOKIE}=`));
if (!localeCookie) {
return defaultLocale;
}
return decodeURIComponent(localeCookie.slice(LOCALE_COOKIE.length + 1));
};
/**
* LocaleProvider component that provides the locale context to its children.
*
* @param {{ locale?: string, children: import('preact').ComponentChildren }} props
*/
export default function LocaleProvider({ locale, children }) {
const detectedLocale = locale ?? detectLocaleFromCookies();
return (
<IntlProvider locale={detectedLocale} messages={{}}>
{children}
</IntlProvider>
);
}