Skip to content

Instantly share code, notes, and snippets.

@vkbansal
Created January 11, 2022 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vkbansal/ba80fe3ac9f2eeb464b506a464c25acd to your computer and use it in GitHub Desktop.
Save vkbansal/ba80fe3ac9f2eeb464b506a464c25acd to your computer and use it in GitHub Desktop.
// StringsContext.tsx
+ import mustache from "mustache";
export interface UseLocaleStringsReturn {
- getString(key: string): string;
+ getString(key: string, variables?: any): string;
}
export function useLocaleStrings() {
const strings = useStringsContext();
return {
- getString(key: string): string {
+ getString(key: string, variables: any = {}): string {
if (has(strings, key)) {
+ const str = get(strings, key);
- return get(strings, key);
+ return mustache.render(str, variables);
}
throw new Error(`Strings data does not have a definition for: "${key}"`);
}
};
}
export interface LocaleStringProps extends HTMLAttributes<any> {
strKey: string;
as?: keyof JSX.IntrinsicElements;
+ variables?: any;
}
export function LocaleString(props: LocaleStringProps): React.ReactElement {
- const { strKey, as, ...rest } = props;
+ const { strKey, as, variables, ...rest } = props;
const { getString } = useLocaleStrings();
const Component = as || "span";
- return <Component {...rest}>{getString(strKey)}</Component>;
+ return <Component {...rest}>{getString(strKey, variables)}</Component>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment