Hi guys,
How can I use the translation in the _document.tsx? I would like use the translation in the meta tags and open graph tags like description and title tags.
Thanks so much!
Internals pages as _app.js and _document.js are not involved with translations for now. There is an open issue for this: https://github.com/vinissimus/next-translate/issues/44
Maybe documentLang can help you, and depending on the language load one locale or another. The problem is that you need to import the JSONs for all the languages, but you can use a small JSON for just the _document.js. Something like:
import Document, { Html, Head, Main, NextScript } from 'next/document'
import documentLang from 'next-translate/documentLang'
import useTranslation from 'next-translate/useTranslation'
import I18nProvider from 'next-translate/I18nProvider'
import metainfoES from '../../locales/es/metainfo.json'
import metainfoEN from '../../locales/en/metainfo.json'
const namespaces = {
es: metainfoES,
en: metainfoEN,
}
export default class MyDocument extends Document {
render() {
const lang = documentLang(this.props)
return (
<Html lang={lang}>
<I18nProvider lang={lang} namespaces={{ metainfo: namespaces[lang] }}>
<CustomHead />
</I18nProvider>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
function CustomHead() {
const {聽t } = useTranslation()
const title = t`metainfo:title`
const description = t`metainfo:description`
return (
<Head>
<title>{title}</title>
<meta name="description" content={description} />
</Head>
)
}
Thanks so much!
Cool, if this solves your problems, I'll close the issue, as there is already another one to better address the issue of translations in internal pages of next.js such as _app.js and _document.js.
Most helpful comment
Cool, if this solves your problems, I'll close the issue, as there is already another one to better address the issue of translations in internal pages of next.js such as
_app.jsand_document.js.