Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set HTML lang attribute dynamically on NextJs Document?

I have a multi language site and need to set up the HTML lang attribute according the language for the each page.

I try to pass the value in context, but does not update when page changes.

Here the current code:

import Document, { Html, Head, Main, NextScript } from 'next/document'
import GlobalContext , {eLanguage }from '../components/GlobalContext' //my global context 

export default class MyDocument extends Document {

static async getInitialProps(ctx) {

  const initialProps = await Document.getInitialProps(ctx)
  return { ...initialProps }
}
static contextType = GlobalContext;
render() {

  console.debug('Started')
  console.debug('language:'+ this.context.language) 

  return (
    <Html lang={eLanguage[this.context.language]}> //if the first page loaded as lang 'en' it sets 'en' and apply to all other pages.
      <Head>
      </Head>
      <body>       
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

}

Update: The language of each page can be inferred from the page route

like image 442
MiguelSlv Avatar asked Apr 19 '20 19:04

MiguelSlv


People also ask

How to add lang in Next js?

Adding this lang tag to Next. js, we don't have direct access to it. So to add this tag, we need to use the next. config. js file.

What is a lang attribute in HTML?

The HTML lang attribute is used to identify the language of text content on the web. This information helps search engines return language specific results, and it is also used by screen readers that switch language profiles to provide the correct accent and pronunciation.


2 Answers

Next 10 supports Internationalized Routing and will add lang dynamically leaving you with:

<Html>
  <Head />
  <body>       
    <Main />
    <NextScript />
  </body>
</Html>
like image 176
vhs Avatar answered Sep 20 '22 21:09

vhs


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

like image 23
Joel Varty Avatar answered Sep 19 '22 21:09

Joel Varty