Tim VanderZwaag
Tim VanderZwaag

Reputation: 33

How do I include embed code with an external script in the body of a Gatsby site?

I'm working on my first Gatsby site and am good to go except for an embed code that needs to be placed in the body of one of the pages. I've looked at the documentation for SSR API's and can't seem to find any clear documentation as to how this is done. The code that needs to be embedded is below. Any help would be appreciated.

The embed code below only needs to go in the body of one page (not every page on the site)?

<style>.vagaro a {font-size:10px; color:#AAA; text-decoration:none;}</style>
<script type="text/javascript" src="https://www.vagaro.com//resources/WidgetEmbeddedLoader/OZqnC30tDZCcT3q"></script>
</div>

Upvotes: 2

Views: 572

Answers (1)

ksav
ksav

Reputation: 20821

If you need at add this stuff to every page, you can do this with html.js.

First make a copy of the existing html.js so that you can make persistent changes:

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

Then clear the cache and public folders: gatsby clean

Then edit src/html.js with your required code before the closing of the <head>.

import React from "react"
import PropTypes from "prop-types"

export default function HTML(props) {
  return (
    <html {...props.htmlAttributes}>
      <head>
        <meta charSet="utf-8" />
        <meta httpEquiv="x-ua-compatible" content="ie=edge" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
        {props.headComponents}
        <style>{`.vagaro a {font-size:10px; color:#AAA; text-decoration:none;}`}</style>
        <script type="text/javascript" src="https://www.vagaro.com//resources/WidgetEmbeddedLoader/OZqnC30tDZCcT3q"></script>
      </head>
      <body {...props.bodyAttributes}>
        {props.preBodyComponents}
        <div
          key={`body`}
          id="___gatsby"
          dangerouslySetInnerHTML={{ __html: props.body }}
        />
        {props.postBodyComponents}
      </body>
    </html>
  )
}

HTML.propTypes = {
  htmlAttributes: PropTypes.object,
  headComponents: PropTypes.array,
  bodyAttributes: PropTypes.object,
  preBodyComponents: PropTypes.array,
  body: PropTypes.string,
  postBodyComponents: PropTypes.array,
}

If you only need to add it to a single page, use react-helmet

import React from 'react';
import Helmet from 'react-helmet';

const SecondPage = () => {
  return (
    <>
      <Helmet>
        <title>Page Two</title>
        <style>{`.vagaro a {font-size:10px; color:#AAA; text-decoration:none;}`}</style>
        <script type="text/javascript" src="https://www.vagaro.com//resources/WidgetEmbeddedLoader/OZqnC30tDZCcT3q"></script>
      </Helmet>
      <h1>Page Two</h1>
      <p>Welcome to page 2</p>
    </>
  );
};

export default SecondPage;

Upvotes: 1

Related Questions