Customizing html.js

Gatsby uses a React component to render <head><footer>, and other elements that lie outside the core application destined for the browser. For the vast majority of Gatsby sites, the html.js file that comes packaged with Gatsby suits most requirements, but some situations call for additional customization. To customize your site’s default html.js, execute the following in the root of your Gatsby project:

$ gatsby build
$ cp .cache/default-html.js src/html.js

This creates an html.js file that overrides Gatsby’s own.

TIP

Customization of the html.js file is recommended by Gatsby only when the appropriate Gatsby Server-Side Rendering APIs implemented in gatsby-ssr.js are not sufficient for your needs. Before performing this customization, consider implementing the onRenderBody or onPreRenderHTML APIs instead. Plugin authors should explore using setPostBodyComponents.

Certain props found within the html.js file are required for Gatsby to perform rendering correctly. These are:

  • headComponents
  • preBodyComponents
  • body
  • postBodyComponents

Within the html.js file, you may need to add custom JavaScript that executes entirely outside Gatsby’s purview, to avoid Gatsby’s own JavaScript processing. To insert custom JavaScript, use React’s dangerouslySetInnerHTML attribute as follows:

// src/html.js
<script
  dangerouslySetInnerHTML={{
    __html: `
      var name = 'world';
      console.log('Hello ' + name);
    `,
  }}
/>
WARNING

If you encounter an error such as the following, your html.js file lacks a required target container in which Gatsby can perform certain actions:

Uncaught Error: _registerComponent(...):
Target container is not a DOM element.

To resolve this error, insert a <div> element with an id attribute of ___gatsby, such as the following:

<div
  key={`body`}
  id="___gatsby"
  dangerouslySetInnerHTML={{ __html: this.props.body
}}
/>

Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *