gatsby icon indicating copy to clipboard operation
gatsby copied to clipboard

chore(docs): gatsby-head example using pageContext and setHtmlAttributes

Open manusa opened this issue 2 years ago • 2 comments

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

manusa avatar Aug 10 '22 12:08 manusa

Where do you get the loadPageDataSync function? I desperately need this for a site I'm working on.

kalebheitzman avatar Aug 12 '22 02:08 kalebheitzman

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.

manusa avatar Aug 12 '22 04:08 manusa

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

byronwilliams avatar Dec 07 '22 12:12 byronwilliams

Does this mean there's no way to change the language based on the page being rendered?

xavivars avatar Jan 04 '23 13:01 xavivars

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 });
  }
}

byronwilliams avatar Jan 04 '23 13:01 byronwilliams

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

LekoArts avatar Jan 19 '23 11:01 LekoArts