Gatsby set lang attribute to html
Asked Answered
L

5

21

How would you do it? modify the public folder doesn't seem to work... make your own build and host it how it is? maybe there is a function that I still don't know. Any help is appreciated.

Lir answered 23/10, 2020 at 16:14 Comment(0)
F
37

Gatsby v5

Gatsby now has its own Head API: https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-head/

Export a head component from your page file, including the html element:

export function Head() {
  return (
    <>
      <html lang="en" />
    </>
  )
}

Outdated:

Gatsby recommends using react helmet for this. You can find a lot of best practices around this topic if you look at the Gatsby documentation - how to add meta data.

Follow the step by step guide in the documentation. React helmet is really powerful. Coming back to your question, that's how you can alter the HTML language attribute:

<Helmet
  htmlAttributes={{
    lang: 'en',
  }}
/>

Faunia answered 23/10, 2020 at 16:16 Comment(1)
This is not the way to do it in 2022. Gatsby recommend using Gatsby Head which is built-in: gatsbyjs.com/docs/reference/built-in-components/gatsby-headHouston
S
9

According to the new Head Api doc (added in [email protected]) you can avoid the Helmet dependency including inside the gatsby-ssr.js or gatsby-ssr.ts file, using the setHtmlAttributes function.

exports.onRenderBody = ({ setHtmlAttributes }) => {
  setHtmlAttributes({ lang: "en" })
}
Sandler answered 16/12, 2022 at 20:13 Comment(0)
L
2

An alternative to Arthur Violy's answer using the Gatsby Head API and ES6:

export const onRenderBody = ({ setHtmlAttributes }) => {
  setHtmlAttributes({ lang: "en" });
};
Letta answered 10/2, 2023 at 10:24 Comment(0)
F
-1

Just an add-in to @Andre's answer, in case you want to use the Open Graph protocol property, e.g: xmlns:og, xmlns:fb... Just wrap the key with the single quote '

<Helmet htmlAttributes={
    {
    lang: 'en',
    'xmlns:og': 'http://ogp.me/ns#',
    'xmlns:fb': 'http://ogp.me/ns/fb#'
    }
  }>

    <meta charSet="utf-8" />
    <meta content="width=device-width, initial-scale=1.0" name="viewport" />
    ....
</Helmet>
Frannie answered 24/5, 2022 at 15:3 Comment(0)
F
-1

if using gatsby v5

Just place

return ( <> <html lang="en" /> </>)

Into Header function

Fuzee answered 27/11, 2023 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.