'(Gatsby) Easiest way to diverge from the `SEO.defaultProps` on a per-document basis?
Most of the pages on my website are in Norwegian—
Seo.defaultProps = {
lang: `no`,
...
}
Some articles, however, are in English.
I use some automatic CSS hyphenation on my website. Thus, I need to set the HTML lang
to English in the head
of these documents so that the words break properly.
I'm not interested in building a full-scale multilingual site. I just want to be able to diverge from the default language property on a per-document basis.
What's the absolute easiest way to do this? Do I need to change my gatsby-node.js
file? Or could I set my template.js
file to ask for a lang
within each MDX file? Or could I maybe insert an seo-english.js
component within the articles I wish to change?
Solution 1:[1]
I found it easiest to use Helmet
in those posts in which I wished to diverge from the default props.
<Helmet
htmlAttributes={{
lang: 'en'
}}
/>
Solution 2:[2]
I think the easiest way is to pass to each article the language in which are they written using the context (pageContext
).
In your createPage
function:
createPage({
path: node.slug,
component: blogPostTemplate,
context: {
lang: node?.lang ?? 'en',
},
})
In your blogPostTemplate
:
function BlogTemplate({ pageContext }) {
const { lang } = pageContext
return (
<div>
Language is: {lang}
</div>
)
}
I think is the most straightforward solution because you are already looping through all articles to create all the pages so you are taking advantage of the loop to get each specific language data. Then, you only need to gather it.
The approach is quite similar to adding the lang in each specific MDX file and fetching it in the template, it doesn't change the workaround. In the end, you will need to add it to the MDX file somehow. If it's not present, it will use en
as a fallback (node?.lang ?? 'en'
).
Using one of those approaches, you can still render on SEO component or another accordingly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Magnus Kolstad |
Solution 2 | Ferran Buireu |