How to handle form submission events in HubSpot form within React component

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?

You need to modify your ContactForm component to accept the callback prop and pass it to the HubSpot form config. Use the onFormSubmitted callback in the hbspt.forms.create options. Here’s how I solved this:

interface ContactFormProps {
  onSubmit?: () => void
}

const ContactForm: React.FC<ContactFormProps> = ({ onSubmit }) => {
  useEffect(() => {
    const formScript = document.createElement('script')
    formScript.src = 'https://js.hsforms.net/forms/v2.js'
    document.body.appendChild(formScript)

    formScript.addEventListener('load', () => {
      if (window.hbspt) {
        window.hbspt.forms.create({
          portalId: '12345678',
          formId: 'abcd-efgh-1234',
          target: '#contactFormContainer',
          onFormSubmitted: function() {
            if (onSubmit) {
              onSubmit()
            }
          }
        })
      }
    })
  }, [onSubmit])

  return (
    <div className="contact-wrapper">
      <div id="contactFormContainer" />
    </div>
  )
}

Use onFormSubmitted instead of onFormSubmit - the first fires after successful submission, the second fires before validation. Don’t forget to add onSubmit to the useEffect dependency array so the form recreates if the callback changes.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.