From 6727c42f1895c2534acb060d560ee6d1032d8e4c Mon Sep 17 00:00:00 2001 From: utin-francis-peter Date: Thu, 4 Jul 2024 10:05:54 +0100 Subject: [PATCH] feat: auto browser lang detection on first visit --- frontend/src/locale/i18n.ts | 42 +++++++++++++++++++++++-------------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/frontend/src/locale/i18n.ts b/frontend/src/locale/i18n.ts index 32b25db..02c5593 100644 --- a/frontend/src/locale/i18n.ts +++ b/frontend/src/locale/i18n.ts @@ -1,29 +1,39 @@ import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; +import LanguageDetector from 'i18next-browser-languagedetector'; import en from './en.json'; //English import es from './es.json'; //Spanish import jp from './jp.json'; //Japanese import zh from './zh.json'; //Mandarin -i18n.use(initReactI18next).init({ - resources: { - en: { - translation: en, +i18n + .use(LanguageDetector) + .use(initReactI18next) + .init({ + resources: { + en: { + translation: en, + }, + es: { + translation: es, + }, + jp: { + translation: jp, + }, + zh: { + translation: zh, + }, }, - es: { - translation: es, + fallbackLng: 'en', + detection: { + order: ['localStorage', 'navigator'], // checks localStorage for existing lang before browser's + caches: ['localStorage'], //stores detected lang to localStorage with i18nextLng key + lookupLocalStorage: 'docsgpt-locale', //using docsgpt-locale as the custom key for storing and retrieving the lang rather than the default `i18nextLng` }, - jp: { - translation: jp, - }, - zh: { - translation: zh, - }, - }, -}); + }); -const locale = localStorage.getItem('docsgpt-locale') ?? 'en'; -i18n.changeLanguage(locale); +const savedLocale = localStorage.getItem('docsgpt-locale') ?? i18n.language; +i18n.changeLanguage(savedLocale); export default i18n;