1- import React , { useState , useEffect } from ' react' ;
2- import { I18nProvider as LinguiI18nProvider } from ' @lingui/react' ;
3- import { i18n , initI18n } from ' ./i18n' ;
1+ import React , { useState , useEffect } from " react" ;
2+ import { I18nProvider as LinguiI18nProvider } from " @lingui/react" ;
3+ import { i18n , initI18n } from " ./i18n" ;
44
55interface I18nProviderProps {
66 locale ?: string ;
77 children : React . ReactNode ;
88}
99
10- export const I18nProvider : React . FC < I18nProviderProps > = ( {
11- locale = 'en' ,
12- children
10+ export const I18nProvider : React . FC < I18nProviderProps > = ( {
11+ locale,
12+ children,
1313} ) => {
1414 const [ isI18nInitialized , setIsI18nInitialized ] = useState ( false ) ;
15+ const effectiveLocale = locale || detectBrowserLocale ( ) ;
1516
1617 useEffect ( ( ) => {
1718 const setupI18n = async ( ) => {
18- await initI18n ( locale ) ;
19+ await initI18n ( effectiveLocale ) ;
1920 setIsI18nInitialized ( true ) ;
2021 } ;
21-
22+
2223 setupI18n ( ) ;
23- } , [ locale ] ) ;
24+ } , [ effectiveLocale ] ) ;
2425
2526 if ( ! isI18nInitialized ) {
2627 // You can replace this with a loading indicator if needed
2728 return null ;
2829 }
2930
30- return (
31- < LinguiI18nProvider i18n = { i18n } >
32- { children }
33- </ LinguiI18nProvider >
34- ) ;
35- } ;
31+ return < LinguiI18nProvider i18n = { i18n } > { children } </ LinguiI18nProvider > ;
32+ } ;
33+
34+ /**
35+ * Detects the browser's preferred language
36+ * @returns The detected browser locale or 'en' as fallback
37+ */
38+ function detectBrowserLocale ( ) : string {
39+ if ( typeof window === "undefined" ) {
40+ return "en" ; // Default for server-side rendering
41+ }
42+
43+ // Use navigator language APIs to get the user's preferred language
44+ const browserLocale =
45+ navigator . languages ?. [ 0 ] ||
46+ navigator . language ||
47+ ( navigator as any ) . userLanguage ||
48+ ( navigator as any ) . browserLanguage ||
49+ "en" ;
50+
51+ return browserLocale ;
52+ }
0 commit comments