PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 20, 2022

[FIXED] How to set HTML lang attribute dynamically on NextJs Document?

 October 20, 2022     html, next.js, node.js, reactjs     No comments   

Issue

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


Solution

Using document object the lang attribute can be set like this:

var language= ...
switch (language) {
    case en:  document.documentElement.lang = 'en-us'; break;
    ...
}

This lang attribute will not be set on the initial html, before page is hydrated, but will still pass chrome "hreflang" audit check.



Answered By - MiguelSlv
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing