Mark Pelling
Mark Pelling

Reputation: 11

Add onSubmit event listener on hubspot form embedded react component

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

Upvotes: 0

Views: 572

Answers (2)

Mark Pelling
Mark Pelling

Reputation: 11

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>
  )
}

Upvotes: 0

Jorge P&#233;rez
Jorge P&#233;rez

Reputation: 244

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

Upvotes: 0

Related Questions