skip to Main Content

I followed this approach of embedding a hubspot form on a react component

HubspotForm.tsx

import React, { useEffect } from 'react'
import './HubspotForm.scss'

const HubspotForm = () => {
  useEffect(() => {
    const script = document.createElement('script')

    script.src = 'https://js.hsforms.net/forms/v2.js'
    document.body.appendChild(script)

    script.addEventListener('load', () => {
      // @TS-ignore
      if (window.hbspt) {
        // @TS-ignore
        window.hbspt.forms.create({
          portalId: '*****',
          formId: '*****',
          target: '#hubspotForm',
          //onFormSubmit: function ($form) {},
        })
      }
    })
  }, [])

  return (
    <div className="form-container">
      <form id="hubspotForm" />
    </div>
  )
}

export default HubspotForm

I need to be able to add a onSubmit event listener inside the form and pass on a function inside it

Ideally:

App.tsx

const App = () => {
    const [isSuccessShown, setIsSuccessShown] = useState<boolean>(false)
    const handleSubmit = (): void => {setIsSuccessShown(true)}

    return (
        <>
          <HubspotForm
           //onSubmit={handleSubmit} ==> I need this to be added
          />
        </>
      );
};

I tried different approaches to add onSubmit event listener but none of them seems to work

2

Answers


  1. Chosen as BEST ANSWER

    Added the following code for onFormSubmit and seems to work just fine

    const HubspotForm = ({onSubmit}) => {
      useEffect(() => {
        const script = document.createElement('script')
    
        script.src = 'https://js.hsforms.net/forms/v2.js'
        document.body.appendChild(script)
    
        script.addEventListener('load', () => {
          // @TS-ignore
          if (window.hbspt) {
            // @TS-ignore
            window.hbspt.forms.create({
              portalId: '*****',
              formId: '*****',
              target: '#hubspotForm',
              onFormSubmit: function ($form) {
              var formData = $form.serializeArray()
              onSubmit(formData)
              },
            })
          }
        })
      }, [])
    
      return (
        <div className="form-container">
          <form id="hubspotForm" />
        </div>
      )
    }


  2. Receive onSubmit in your HubspotForm.tsx, like so:

    const HubspotForm = ({onSubmit}) => {
       // now you can call onSubmit, which points to handleSubmit
    }
    

    Don’t forget to uncomment the line in App.tsx

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search