I’m working on integrating a HubSpot form into my React application and need to trigger custom actions when the form gets submitted. Here’s my current setup:
ContactForm.tsx
import React, { useEffect } from 'react'
import './ContactForm.scss'
const ContactForm = () => {
useEffect(() => {
const formScript = document.createElement('script')
formScript.src = 'https://js.hsforms.net/forms/v2.js'
document.body.appendChild(formScript)
formScript.addEventListener('load', () => {
// @TS-ignore
if (window.hbspt) {
// @TS-ignore
window.hbspt.forms.create({
portalId: '12345678',
formId: 'abcd-efgh-1234',
target: '#contactFormContainer',
//onFormSubmit: function (form) {},
})
}
})
}, [])
return (
<div className="contact-wrapper">
<div id="contactFormContainer" />
</div>
)
}
export default ContactForm
What I want to achieve is passing a callback function from the parent component to handle form submissions:
MainApp.tsx
const MainApp = () => {
const [showSuccess, setShowSuccess] = useState<boolean>(false)
const onFormSubmit = (): void => {setShowSuccess(true)}
return (
<div>
<ContactForm
//onSubmit={onFormSubmit} ==> Need to implement this
/>
</div>
);
};
I’ve tried several methods to capture the form submission event but haven’t found a working solution yet. Any suggestions on how to properly implement this?