gatsby
gatsby copied to clipboard
chore(docs): gatsby-head example using pageContext and setHtmlAttributes
Description
New example in https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-head/#editing-html-and-body showing how to use setHtmlAttributes with dynamic values provided by the pageContext
.
Documentation
Related Issues
Related to https://github.com/gatsbyjs/gatsby/discussions/35841#discussioncomment-3365765
Where do you get the loadPageDataSync
function? I desperately need this for a site I'm working on.
Where do you get the
loadPageDataSync
function? I desperately need this for a site I'm working on.
:facepalm: there was a copy-paste mistake. I've updated the example, everything should be clearer now.
Also note that the function is only populated when building production, I'm not sure if this should be reported as a bug, and fixed, or it's part of the expected behavior.
This PR cannot be merged as loadPageDataSync
does not exist as a prop in 4.24.0
.
The PR that was merged - https://github.com/gatsbyjs/gatsby/pull/36492 - has updated the types but not actually added loadPageDataSync
as a prop to onRenderBody
. As of 4.24.0
this is what is sent in to onRenderBody
as props:
{
setHeadComponents: [Function: setHeadComponents],
setHtmlAttributes: [Function: setHtmlAttributes],
setBodyAttributes: [Function: setBodyAttributes],
setPreBodyComponents: [Function: setPreBodyComponents],
setPostBodyComponents: [Function: setPostBodyComponents],
setBodyProps: [Function: setBodyProps],
pathname: '/'
}
Or this PR should mark it as optional as it's not present in non production
envs
Does this mean there's no way to change the language based on the page being rendered?
Yes, you can do it. It will just won't show up in dev, or type check correctly:
export const onRenderBody: GatsbySSR["onRenderBody"] = (props) => {
// only exists when NODE_ENV === "production" in v4.24.0
if (props.loadPageDataSync) {
const { loadPageDataSync, setHtmlAttributes, pathname } = props;
const { pageContext } = loadPageDataSync(pathname).result as Record<
string,
PageContext
>;
setHtmlAttributes({ lang: pageContext.locale });
}
}
Hi!
With https://github.com/gatsbyjs/gatsby/pull/37449 merged there won't be a need anymore for this workaround using an API we don't really want people to use. It'll be released in Gatsby 5.5