How to set HTML lang attribute dynamically on NextJs Document?
Solution 1:
Next 10 supports Internationalized Routing and will add lang
dynamically leaving you with:
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
Solution 2:
I implemented this by adding this to next.config.js file:
i18n: {
// These are all the locales you want to support in
// your application
locales: ['en-US'],
// This is the default locale you want to be used when visiting
// a non-locale prefixed path e.g. `/hello`
defaultLocale: 'en-US' }
I didn't have the need to create a custom _document.js
Solution 3:
I believe the best solution here is to use a custom ./pages/_document.js
file and override the document itself.
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}
render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
More explanation can be found here: https://nextjs.org/docs/advanced-features/custom-document
Solution 4:
If you use next/head you can set the language to the html tag. Anything that you pass to the Head component will be either placed in the <head>
or <html>
.
Next Head works similar to React Helmet, so for your case you could do something along these lines:
- Create a component and import Head from "next/head"
- Inside the Head tag you add the
<html lang={lan} />
to the component.
Then you can pass the desired language to that component, then import the component on the desired pages.
import React from "react"
import Head from "next/head"
const Language = ({title, lang}) => (
<Head>
<html lang={lang} />
<title>{title}</title>
</Head>
)
export default Language
That html bit will be injected inside the <html>
tag.
Note that even if we inject it like this the console will log the following error: TypeError: n is null
.