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?
Figured it out. You need the following code in componentDidMount to ensure the external js is loaded first.
Hope this helps anyone stuck with the same thing.