I am trying to add a Trustpilot TrustBox to a Next.js app.
I have this in my ponentDidMount:
var trustbox = document.getElementById('trustbox');
window.Trustpilot.loadFromElement(trustbox);
This in my Head:
<script type="text/javascript" src="//widget.trustpilot/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="" 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?
I am trying to add a Trustpilot TrustBox to a Next.js app.
I have this in my ponentDidMount:
var trustbox = document.getElementById('trustbox');
window.Trustpilot.loadFromElement(trustbox);
This in my Head:
<script type="text/javascript" src="//widget.trustpilot./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./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?
Share Improve this question asked Sep 24, 2018 at 9:56 JonnyJonny 1411 silver badge5 bronze badges2 Answers
Reset to default 11Figured it out. You need the following code in ponentDidMount to ensure the external js is loaded first.
ponentDidMount() {
var aScript = document.createElement('script');
aScript.type = 'text/javascript';
aScript.src = "//widget.trustpilot./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.
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...