React-i18next: How to make the lang and dir attributes of the html tag reflect the current language?

Created on 17 Aug 2019  路  4Comments  路  Source: i18next/react-i18next

Hi,

Thank you for this amazing framework,

I use create react app to create my project and I want the lang and dir attributes of the html tag to reflect the current language?

How to do that please?

All the best,
Mohammed

Most helpful comment

That's ok...or use i18next.on('languageChanged', (lng) => {document.documentElement.setAttribute('lang', lng);})

All 4 comments

I used React Helmet and put the following in the App.js file and it worked:

<Helmet htmlAttributes={{ lang : this.props.i18n.language, dir: this.props.i18n.dir() }}/>

Is this ok or is there an i18next way to do this?

That's ok...or use i18next.on('languageChanged', (lng) => {document.documentElement.setAttribute('lang', lng);})

@jamuhl Thanks a lot!

If the user is not allowed to change the language but it derives by other means, then I simply add this line of code to my i18next configuration file:

// my configuration
i18n
  .use(initReactI18next) 
  .init({
    resources: {
      ...
    },
    ...
  })

document.documentElement.lang = i18n.language  // <---- this line right here

If the user is allowed to change the language then this line above should be placed where the language is changed

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Flo-Slv picture Flo-Slv  路  4Comments

a-barbieri picture a-barbieri  路  4Comments

ezze picture ezze  路  4Comments

tankpower1 picture tankpower1  路  3Comments

ChCosmin picture ChCosmin  路  4Comments