Last active
January 11, 2019 10:30
-
-
Save kaneel/cf713e4a16aa3b411903b8fa2bade8a8 to your computer and use it in GitHub Desktop.
Quick i18n solution with a dict saved in a Redux store
This file contains hidden or 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 * as React from 'react'; | |
import { connect } from 'react-redux'; | |
import { Store } from '../../../store'; | |
export interface I18nTextProps { | |
text: string | string[]; | |
hasInnerHTML?: boolean; | |
vars?: any; | |
} | |
export interface I18nTextStateProps { | |
text: string[]; | |
originalKey: string[]; | |
} | |
export const i18nmap = (text: string , dict: Store.Dict) => dict[text] || text; | |
export const i18nMapStateToProps = (state: Store.All, {text}: I18nTextProps) => ({ | |
text: typeof text === 'string' ? [i18nmap(text, state.dict)] : text.map((item: string) => i18nmap(item, state.dict)), | |
originalKey: typeof text === 'string' ? [text] : text | |
}); | |
export const replaceVars: (text: string, vars: any) => string = (text, vars = {}) => text.replace(/%(\w+)%/g, (found: string, key: string, index: number) => vars[key]); | |
export class Text extends React.Component<I18nTextProps & I18nTextStateProps, {}> { | |
public static defaultProps: Partial<I18nTextProps & I18nTextStateProps> = { | |
hasInnerHTML: false, | |
vars: null | |
}; | |
public render() { | |
const { hasInnerHTML, vars, text, originalKey, children } = this.props; | |
return typeof children === 'function' ? | |
(children as any).apply(null, text.map((item: string) => replaceVars(item, vars))) || null : hasInnerHTML ? | |
text.map((item: string, i: number) => <span key={i} className="i18ntext" data-original-key={originalKey[i]} dangerouslySetInnerHTML={{__html: replaceVars(item, vars)}} />) : | |
text.map((item: string, i: number) => <span key={i} className="i18ntext" data-original-key={originalKey[i]}>{replaceVars(item, vars)}</span>); | |
} | |
} | |
// tslint:disable-next-line: variable-name | |
export const I18nText = connect(i18nMapStateToProps)(Text) as React.ComponentClass<I18nTextProps>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment