Why does javascript not not fire on page change in Gatsby project?

I have a trustpilot widget that renders fine on initial load. Then when i change pages, the trustpilot widget resorts back to default logo with no data showing.

I tried removing the external trustpilot js within componentDidMount, then adding it back in, to try refresh but didnt work.

I thought I could manually add in the trustpilot html again. Is there a way to do this in gatsby? and will this work? the below didnt work.

$('#trustpilot').after('<div class="trustpilot-widget trustpilot-carousel" data-locale="...

4 thoughts on “Why does javascript not not fire on page change in Gatsby project?”

  1. Because you are adding jQuery selectors (pointing directly to the DOM) in a React-based project, mixing different stuff and logic. While with React, you are creating and manipulating a virtual DOM (vDOM), which is hydrated on-demand by React.

    When you change the page, the <div> that you are requesting may not be rendered yet or your code changes are not being persisted (mount/unmount and rehydration issues).

    I thought I could manually add in the trustpilot html again. Is there
    a way to do this in gatsby?

    Something that may work for you is to use the gatsby-browser.js and gatsby-ssr.js APIs, specifically the wrapRootElement/wrapPageElement. Both of them will wrap your code (used in both files) and will avoid the unmounting components through the pages, persisting your Truspilot widget.

    const React = require("react")
    const Layout = require("./src/components/layout").default
    
    exports.wrapPageElement = ({ element, props }) => {
      return <Layout {...props}>{element}</Layout>
    }
    

    Regarding what you’ve commented so far, customizing the html.js may fit your requirements to add the script, but this won’t save you to unmount the component on each route change.

    Reply

Leave a Comment