Created
April 18, 2024 10:00
-
-
Save GFier/cf1dd9525e5ab7a8ad6871a57736664b to your computer and use it in GitHub Desktop.
Embedded Husbpot forms with Chili Piper integration for Next JS apps.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use client' | |
import Script from 'next/script' | |
import { useEffect } from 'react' | |
export function EmbedHubspotForm({ | |
strategy = 'afterInteractive', | |
formId, | |
chiliRouter = false, | |
target = 'hubspot-form-wrapper', | |
className, | |
}) { | |
// add script on use effect so every time component mounts it will add the script | |
// Script of next js avoids this as optimization | |
useEffect(() => { | |
const onLoad = () => { | |
window.hbspt.forms.create({ | |
portalId: process.env.NEXT_PUBLIC_HUSBPOT_PORTAL_ID, | |
formId, | |
target: '#' + target, | |
}) | |
} | |
if (document.querySelector('#hubspotScript')) return | |
const script = document.createElement('script') | |
script.id = 'hubspotScript' | |
script.async = true | |
script.src = 'https://js.hsforms.net/forms/v2.js' | |
script.type = 'text/javascript' | |
document.body.appendChild(script) | |
script.addEventListener('load', onLoad) | |
return () => { | |
if (script) { | |
script.removeEventListener('load', onLoad) | |
document.body.removeChild(script) | |
} | |
} | |
}, [formId, target]) | |
return ( | |
<div id={target} className={className}> | |
{chiliRouter && ( | |
<Script | |
strategy={strategy} | |
src="https://js.chilipiper.com/marketing.js" | |
onLoad={() => { | |
var lead = {} | |
window.addEventListener('message', function (event) { | |
if (event.data.type === 'hsFormCallback') { | |
if (event.data.eventName === 'onFormSubmit') { | |
window.dataLayer.push({ event: 'hs-form-submit' }) | |
for (var key in event.data.data) { | |
if (Array.isArray(event.data.data[key].value)) { | |
event.data.data[key].value = event.data.data[key].value | |
.toString() | |
.replaceAll(',', ';') | |
} | |
lead[event.data.data[key].name] = event.data.data[key].value | |
} | |
if (Object.keys(lead).length <= 1) { | |
lead = event.data.data | |
} | |
} else if (event.data.eventName === 'onFormSubmitted') { | |
ChiliPiper.submit('your-key', chiliRouter, { | |
map: true, | |
lead: lead, | |
}) | |
} | |
} | |
}) | |
}} | |
/> | |
)} | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment