Trustpilot TrustBoxes in Next.js

5.7k Views Asked by At

I am trying to add a Trustpilot TrustBox to a Next.js app.

I have this in my componentDidMount:

 var trustbox = document.getElementById('trustbox');
 window.Trustpilot.loadFromElement(trustbox);

This in my Head:

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

And this in my html:

<div id="trustbox" className="trustpilot-widget" data-locale="en-GB" data-template-id="XX" data-businessunit-id="XX" data-style-height="130px" data-style-width="100%" data-theme="light" data-stars="5" data-schema-type="Organization">
    <a href="https://uk.trustpilot.com/review/XX" target="_blank">Trustpilot</a>
</div>

This works fine on hot reload. E.g. if I add the code while the server is running. But o fresh re-load it breaks and I get the following error:

Cannot read property 'loadFromElement' of undefined

Any ideas?

2

There are 2 best solutions below

0
On

For future readers, Trustpilot has now a documentation for single page apps that you can find here

I was wondering why nothing was rendered even with their official documentation but after 2 hours of pain I found out that (at the time i am writing this) you can't load their widget on the Brave navigator...

1
On

Figured it out. You need the following code in componentDidMount to ensure the external js is loaded first.

componentDidMount() {
    var aScript = document.createElement('script');
    aScript.type = 'text/javascript';
    aScript.src = "//widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js";
    aScript.async = "true"
    document.head.appendChild(aScript);
    aScript.onload = function () {
        var trustbox = document.getElementById('trustbox');
        window.Trustpilot.loadFromElement(trustbox);
    };
}

Hope this helps anyone stuck with the same thing.