Skip to content

Instantly share code, notes, and snippets.

@swcho
Last active April 24, 2017 06:03
Show Gist options
  • Save swcho/ed591cfc015bb278a8b3f4864aaad571 to your computer and use it in GitHub Desktop.
Save swcho/ed591cfc015bb278a8b3f4864aaad571 to your computer and use it in GitHub Desktop.
React i18n
ReactDOM.render((
<Provider store={store}>
<IntlProvider {...getIntlProviderParam()}>
<Router history={history as any}>
<Route component={Pattern} onChange={redirector()}>
<Route path={PATH_INPUT} component={Input}/>
<Route path={PATH_LIST} component={List}/>
<Route path={PATH_EDITOR} component={Editor}/>
<Route path='/tableinput' component={TableInput}/>
<Route path='/itemlist' component={ItemList}/>
<Route path='/multipleradio' component={MultipleRadio}/>
</Route>
<Redirect from='*' to='/input'/>
</Router>
</IntlProvider>
</Provider>
), document.querySelector('#react-app')); ;
import { addLocaleData } from 'react-intl';
import * as en from 'react-intl/locale-data/en';
import * as ko from 'react-intl/locale-data/ko';
addLocaleData([...en, ...ko]);
export type SUPPORTED_LANG = {
'en': string;
'ko': string;
};
export type SUPPORTED_LANG_TYPE = keyof SUPPORTED_LANG;
export const SUPPORTED_LANG_LIST: SUPPORTED_LANG_TYPE[] = ['en' , 'ko'];
const DEFAULT_LANG = 'ko';
export interface Locale<T> {
locale: keyof SUPPORTED_LANG;
fields?: { [key in keyof T]: string };
pluralRuleFunction?: (n: number, ord: boolean) => string;
}
export type LocaleData<T> = Array<Locale<T>>;
export interface MessageDescriptor<T> {
id: keyof T;
description?: string;
defaultMessage?: string;
}
export type Messages<T> = {
[lang in keyof SUPPORTED_LANG]: { [id in keyof T]: string };
}
export function getFixedLanguage() {
const prefix = location.pathname.slice(0, 3);
return {
'/en': 'en',
'/ko': 'ko'
}[prefix];
}
// Define user's language. Different browsers have the user locale defined
// on different fields on the `navigator` object, so we make sure to account
// for these different by checking all of them
const languageProvided = getFixedLanguage() ||
(navigator['languages'] && navigator['languages'][0]) ||
navigator.language ||
navigator['userLanguage'];
const language = SUPPORTED_LANG_LIST.indexOf(languageProvided) !== -1 ? languageProvided : DEFAULT_LANG;
// Split locales with a region code
const languageWithoutRegionCode = language.toLowerCase().split(/[_-]+/)[0];
let sMessages = {};
export function addMessages(messages: Messages<any>) {
const messagesToAdd = messages[languageWithoutRegionCode] || messages[language] || messages[DEFAULT_LANG];
sMessages = {...sMessages, ...messagesToAdd};
}
export function getIntlProviderParam() {
return {
locale: language,
messages: sMessages
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment