Currently utilizing Next.js and exploring text translation using the 'next-translate/useTranslation' feature.
To ensure only translated strings are displayed, I have implemented a function that checks if the string exists in my translation JSON file ('common'). If found, it returns the translated text, otherwise the original string is shown.
The goal is to extract this translation checking function as a reusable utility that can be applied across all pages.
However, the current approach involves copying the function into every component requiring translation, resulting in repetitive code.
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>
)
}
While I came across a solution for this issue in React but not Next.js: React i18next useTranslation Hook in helper method
Seeking guidance on optimizing this process in Next.js to reduce redundancy. How can I streamline this translation function?