Techstacker
Light ModeDark ModeReset dark mode. Falls back to OS dark mode setting.

Pages

No results for 'undefined'

Blog Posts

No results for 'undefined'
Powered by Algolia

How to Add Custom JavaScript to Your GatsbyJS Site

Oct 12, 20191 min readGatsbyJSViews:

Although GatsbyJS is a React framework, it can be useful to know how to add custom JavaScript to your Gatsby project. Perhaps you just moved your old website to Gatsby, and have a bunch of custom vanilla JavaScript that you don’t really fancy converting to ReactJS syntax right now — I feel ya.

Fortunately adding plain JavaScript to Gatsby isn’† hard at all, you just need to expose a simple file, html.js, which isn’t visible in your Gatsby project by default.

To expose (make available) the html.js file, open your terminal, navigate to the root of your Gatsby project folder, and enter the following:

cp .cache/default-html.js src/html.js

Now html.js is available in your src folder in your Gatsby project.

html.js inside the Gatsby src folder

Inside the html.js file there’s a bunch of HTML syntax that you probably recognize. Don’t touch any of the existing code, but pay attention to the div element with an dangerouslySetInnerHTML attribute. We need to use the same attribute, with the <script> element.

Copy & paste the following snippet right above your html.js file‘s closing body tag </body>:

<script
  dangerouslySetInnerHTML={{
    __html: `
    console.log('Plain JavaScript inside Gatsby!');
`
  }}
/>

Save your changes, and start your Gatsby server, or refresh your browser tab if Gatsby is already running. If you did it correctly, you should see the following message in your chrome console:

Plain JavaScript inside Gatsby!

Try adding a click event with an alert message inside your script element:

document.body.addEventListener('click', function() {
  alert('JavaScript!')
})

Now when you click anywhere on your page, it should pop up with an alert message, saying “JavaScript!”.

Resources:

Check out the official GatsbyJS docs for (adding custom JavaScript)[https://www.gatsbyjs.org/docs/custom-html/#adding-custom-javascript]