Reputation: 43
useEffect(() => {
const script = document.createElement("script");
script.src = "//js-eu1.hsforms.net/forms/embed/v2.js";
document.body.appendChild(script);
script.addEventListener("load", () => {
// @TS-ignore
if (hbspt) {
// @TS-ignore
window.hbspt.forms.create({
portalId: "YOUR_PORTAL_ID_HERE",
formId: "YOUR_FORM_ID_HERE",
target: "#hubspotForm",
});
}
});
}, []);
I found this code for embeding my form to my react component, but I keep getting error
Cannot find name 'hbspt'.
(I am using typescript btw)
Upvotes: 3
Views: 1502
Reputation: 1299
In our case I tried a lot if different things. The only thing that helped, was to use a delay function for the hubspot stuff to get the form to work:
<script charset="utf-8" type="text/javascript" src="https://js-eu1.hsforms.net/forms/embed/v2.js"></script>
<script>
setTimeout(function() {
if(typeof hbspt !== 'undefined') {
hbspt.forms.create({
region: "eu1",
portalId: "123",
formId: "abcdef-0000-0000-0000-abcdef0123456"
});
} else {
console.error('HubSpot-Skript cannot be loaded.');
}
}, 400);
</script>
Upvotes: 1
Reputation: 197
be careful that your code will import the hubspot horrible javascript inside your page multiple times.
consider doing this:
inside the index.html meta parts add the javascript import
<script
charset="utf-8"
type="text/javascript"
src="//js.hsforms.net/forms/embed/v2.js"
></script>
makes the useEffect doing only the placement in the page
useEffect(() => {
/* eslint-disable */
if (hbspt) {
/* eslint-disable */
window.hbspt.forms.create({
region: "[...]",
portalId: "[...]",
formId: "[...]",
target: "#hubspotForm",
});
}
}, []);
Upvotes: 0