Skip to content

Instantly share code, notes, and snippets.

@teramotodaiki
Created May 25, 2019 14:15
Show Gist options
  • Save teramotodaiki/4f72d5a52ca09b1c8e2cc7586462b6d2 to your computer and use it in GitHub Desktop.
Save teramotodaiki/4f72d5a52ca09b1c8e2cc7586462b6d2 to your computer and use it in GitHub Desktop.
Simple localize function implements with React and rxjs
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