Issue
I am using Next.js now and I am trying to do translation on those text with 'next-translate/useTranslation'
As I may not have all strings in the application translated, and I write a checking function to check if the string is in my translation JSON file (common). If it is, return translated string, else just show the original string
The target is that the translation checking function is extracted as a utility function that can be reused in every page.
Current usage: Copy the function into every component needed translation (repeated code in every component therefore)
type Props = {}
const testComponent: FunctionComponent<Props> = () => {
const { t, lang } = useTranslation('common');
//the checking function used
const checkStringTranslated = (string2bChecked:string)=>{
if(t(string2bChecked).includes('common'))return false
return true
}
return (
<div>
<p>{checkStringTranslated("String2bTranslated")?t("String2bTranslated"):"String2bTranslated"}</p>
</div>
)
}
I have found a post that achieves that but not in Next.js: React i18next useTranslation Hook in helper method
And I have no clue how to do that in Next.js. How can I make this less redundant?
Solution
You don't need to create a helper function for it, next-translate
provides that functionality through the default
property in the options
object when calling the t
function from useTranslate
.
const testComponent: FunctionComponent<Props> = () => {
const { t } = useTranslation('common');
return (
<div>
<p>{t("String2bTranslated", undefined, { default: "String2bTranslated" })}</p>
</div>
);
};
Answered By - juliomalves
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.