Created
May 25, 2019 14:15
-
-
Save teramotodaiki/4f72d5a52ca09b1c8e2cc7586462b6d2 to your computer and use it in GitHub Desktop.
Simple localize function implements with React and rxjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { BehaviorSubject } from 'rxjs'; | |
import { useState, useEffect } from 'react'; | |
export type LocaleKeys = 'Press any key' | 'Touch to start'; | |
export type Locale = { [key in LocaleKeys]: string }; | |
const localeMap: { | |
[locale: string]: Locale; | |
} = { | |
en: { | |
'Press any key': 'Press any key', | |
'Touch to start': 'Touch to start' | |
}, | |
ja: { | |
'Press any key': 'キーを押してください', | |
'Touch to start': 'タッチしてください' | |
} | |
}; | |
const internalLanguageCode$ = new BehaviorSubject( | |
navigator.language.split('-')[0] | |
); | |
const setter = (languageCode: string) => { | |
if ( | |
languageCode !== internalLanguageCode$.value && | |
languageCode in localeMap | |
) { | |
internalLanguageCode$.next(languageCode); | |
} | |
}; | |
export const useLocale = (): [Locale, typeof setter] => { | |
const [, forceUpdate] = useState({}); | |
useEffect(() => { | |
const subscription = internalLanguageCode$.subscribe(() => forceUpdate({})); | |
return () => { | |
subscription.unsubscribe(); | |
}; | |
}, []); | |
const locale = localeMap[internalLanguageCode$.value] || localeMap.en; | |
return [locale, setter]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment