Created
January 11, 2022 10:03
-
-
Save vkbansal/ba80fe3ac9f2eeb464b506a464c25acd to your computer and use it in GitHub Desktop.
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
// 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