External script not loading on page change

Viewed 214

I am trying to add a Trustpilot widget to my Gatsby.js website. It is required to load an external script from Trustpilot CDN.

<script type="text/javascript" src="//widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js" async></script>

I have tried multiple ways to add this script to my component. The first thing I tried was React Helmet. I added using the following code:

<Helmet>
<script type="text/javascript" src="//widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js" async></script>

The script seems to load when I initially load a page. Once I navigate to a different page, the styling goes away. As I reload, it comes back.

I tried adding the script inside componentDidMount()

componentDidMount() {
    var addScript = document.createElement('script');
    addScript.setAttribute('src', '//widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js');
    document.body.appendChild(addScript);
}
1 Answers

If you want your script (or any other component) to be persistent through your site, you need to use wrapPageElement or wrapRootElement APIs. Both APIs are suggested to be placed in gatsby-browser.js as well as in gatsby-ssr.js

Disclaimer: componentDidMount() will be triggered every time the DOM tree is loaded, it won't work for your use-case.

The issue here is that you are adding a non-React asset, not a component. You can try:

export const wrapPageElement = ({ element, props }) => {
  return <SomeWrapper {...props}>{element}</SomeWrapper>;
};

Then, create a component called SomeWrapper and place your <Helmet>:

const SomeWrapper = (props) =>{
 return <div>
           <Helmet>
             <script type="text/javascript" src="//widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js" async /> 
          </Helmet>
          {props.children}
    </div>
}
Related