Before next@10, next did not have any built-in support for internationalized routing.
I used next-translate/useTranslation. But the problem I am facing now is that I'm unable to set the lang
attribute.
The only option I've found to set the attribute lang in next@9.4 using a functional component is document.documentElement.lang = lang
which is not a good practice for SEO.
Is there any other way I could use to set the lang of my HTML page dynamically?
This is how my code is :
/pages
- index.js
- /[lang]
- index.js
/pages/index.js
import { useEffect } from 'react'
import Router from 'next/router'
import i18nConfig from '../i18n.json'
const { defaultLanguage } = i18nConfig
export default function Index() {
useEffect(() => {
Router.replace(`/${defaultLanguage}`)
}, [])
return null
}
/[lang]/index.js
import useTranslation from 'next-translate/useTranslation'
import { getI18nProps, getI18nPaths, withI18n } from '../../utils/i18n'
...
export function MainIndex() {
const { t, lang } = useTranslation()
...
useEffect(() => {
document.documentElement.lang = lang
})
...
}
...
export default withI18n(MainIndex)
In case it's needed this is my config file.
i18n.json
{
"allLanguages": [
"fr",
"en"
],
"defaultLanguage": "fr",
"redirectToDefaultLang": false
}
In the documentation they also talk about I18nProvider
to set the lang attribut, but it does not work. No error and no lang attribut set in the document if I use :
<I18nProvider lang={lang}>
...
</I18nProvider>