APIs & Integrations

fabrice
Mitglied

HELP: Embed a form in a React component

lösung

Hi all,

I’m having trouble embedding a hubspot form into a React component. JSX will consider the script tag as a React component itself and try to compile it as such. Have you guys tried to integrate a hubspot form with react before?

Any help would be appreciated! thanks!

fabrice

3 Akzeptierte Lösungen
DHawkings
Lösung
Mitglied

HELP: Embed a form in a React component

lösung

This is great. Worked perfectly for us right away. Thank you!

 

Here is a typescript friendly version (really just supressing the warnings) that uses a functional component and useEffect instead of class component and componentDidMount.

 

import React, {useEffect} from "react";

const HubspotContactForm = () => {
    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: 'YOUR_PORTAL_ID_HERE',
                    formId: 'YOUR_FORM_ID_HERE',
                    target: '#hubspotForm'
                })
            }
        });
    }, []);

    return (
        <div>
            <div id="hubspotForm"></div>
        </div>
    );

}

export default HubspotContactForm;

 

 

Lösung in ursprünglichem Beitrag anzeigen

EdCupaioli
Lösung
Mitglied

HELP: Embed a form in a React component

lösung

I took a different (slightly more complicated) approach but ended up a functioning form. I just added the base script to a Helmet  tag and added the window.hbspt parameter for useEffect. 

const hubspotForm = () => {
useEffect(() => {
    if (window.hbspt) {
      window.hbspt.forms.create({
        portalId: "YOUR-PORTAL-ID",
        formId: "YOUR-FORM-ID",
        target: "YOUR-FORM-CONTAINER-ID"
      });
    }
  },[window.hbspt])
return (
<>
<Helmet>
  <script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2.js"> </script>
</Helmet>
</>
)
}

It's working for me just fine but I'm still a react noob so let me know if it doesn't work for y'all. 

Lösung in ursprünglichem Beitrag anzeigen

DGomez2
Lösung
Mitglied

HELP: Embed a form in a React component

lösung

hello there, there a simple and better way to do that, just install via npm this package

https://www.npmjs.com/package/react-hubspot-form

 import HubspotForm from 'react-hubspot-form'


<HubspotForm
                portalId='22384747'
                formId='556eed30-2d51-4224-86f8-ffa83f0bde15'
                onSubmit={() => console.log('Submit!')}
                onReady={(form) => console.log('Form ready!')}
                loading={<div>Loading...</div>}
            />

 

that work for me and was so easy, also i recomend remove strict mode from your index, i got a problem with that i dont know why but my form was rendering twice, i just removed that and that way i fixed the form, if have question reply 😃 

Lösung in ursprünglichem Beitrag anzeigen

15 Antworten
DGomez2
Lösung
Mitglied

HELP: Embed a form in a React component

lösung

hello there, there a simple and better way to do that, just install via npm this package

https://www.npmjs.com/package/react-hubspot-form

 import HubspotForm from 'react-hubspot-form'


<HubspotForm
                portalId='22384747'
                formId='556eed30-2d51-4224-86f8-ffa83f0bde15'
                onSubmit={() => console.log('Submit!')}
                onReady={(form) => console.log('Form ready!')}
                loading={<div>Loading...</div>}
            />

 

that work for me and was so easy, also i recomend remove strict mode from your index, i got a problem with that i dont know why but my form was rendering twice, i just removed that and that way i fixed the form, if have question reply 😃 

Nicht anwendbar

HELP: Embed a form in a React component

lösung

Hi everyone, I struggled through this issue a bit, but after referencing a couple of different posts online I’ve come to a working solution. Please reference my code example: https://jsfiddle.net/2Lwq9zbg/

Hope this helps. Cheers!

DHawkings
Lösung
Mitglied

HELP: Embed a form in a React component

lösung

This is great. Worked perfectly for us right away. Thank you!

 

Here is a typescript friendly version (really just supressing the warnings) that uses a functional component and useEffect instead of class component and componentDidMount.

 

import React, {useEffect} from "react";

const HubspotContactForm = () => {
    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: 'YOUR_PORTAL_ID_HERE',
                    formId: 'YOUR_FORM_ID_HERE',
                    target: '#hubspotForm'
                })
            }
        });
    }, []);

    return (
        <div>
            <div id="hubspotForm"></div>
        </div>
    );

}

export default HubspotContactForm;

 

 

SSopin
Teilnehmer/-in

HELP: Embed a form in a React component

lösung

Here is a Typescript version without warnings suppression: 

 

 

import {useEffect} from "react";

const SubscriptionForm = () => {
    useEffect(() => {
        const script = document.createElement('script');
        script.src='https://js.hsforms.net/forms/v2.js';
        document.body.appendChild(script);

        script.addEventListener('load', () => {
            if ((window as any).hbspt) {
                (window as any).hbspt.forms.create({
                    portalId: 'YOUR-PORTAL-ID',
                    formId: 'YOUR-FORM-ID',
                    target: '#hubspotForm'
                })
            }
        });
    }, []);

    return (
        <div>
            <div id="hubspotForm"></div>
        </div>
    );

}

export default SubscriptionForm;

 

 

 

0 Upvotes
ivanakcheurov
Teilnehmer/-in

HELP: Embed a form in a React component

lösung

I try this code in Next.js application, the script gets loaded, hbspt.form.create gets executed but the form doesn't show up, so the target remains unchanged.
The solution that worked for me was the answer based on class components.

0 Upvotes
EdCupaioli
Lösung
Mitglied

HELP: Embed a form in a React component

lösung

I took a different (slightly more complicated) approach but ended up a functioning form. I just added the base script to a Helmet  tag and added the window.hbspt parameter for useEffect. 

const hubspotForm = () => {
useEffect(() => {
    if (window.hbspt) {
      window.hbspt.forms.create({
        portalId: "YOUR-PORTAL-ID",
        formId: "YOUR-FORM-ID",
        target: "YOUR-FORM-CONTAINER-ID"
      });
    }
  },[window.hbspt])
return (
<>
<Helmet>
  <script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2.js"> </script>
</Helmet>
</>
)
}

It's working for me just fine but I'm still a react noob so let me know if it doesn't work for y'all. 

PPetkov
Mitglied

HELP: Embed a form in a React component

lösung

That works perfectly and it submitting, but after refreshing the page, the form doesn't load. Any fix to this? Probably somehow using state?

0 Upvotes
Jaycee_Lewis
Community-Manager/-in
Community-Manager/-in

HELP: Embed a form in a React component

lösung

Thanks for adding your solution, @EdCupaioli 🙌

— Jaycee

linkedin

Jaycee Lewis

Developer Community Manager

Community | HubSpot

0 Upvotes
aalstes
Teilnehmer/-in

HELP: Embed a form in a React component

lösung

Aweome, this definitely helped me! Thanks. I used useEffect instead of componentDidMount, with success.

0 Upvotes
CaseyBinkley
Teilnehmer/-in

HELP: Embed a form in a React component

lösung

Since we’re dealing with iframes anyway, I created another iframe pointing to a route that only had the hubspot div and script.

/contact

<iframe className="meetings-wrapper" src="/meetings"></iframe>

/meetings

<html>
  <body>
    <div style="max-width: 500px;" class="meetings-iframe-container" data-src="https://app.hubspot.com/meetings/youruser?embed=true"></div>
    <script type="text/javascript" src="https://static.hsappstatic.net/MeetingsEmbed/ex/MeetingsEmbedCode.js"></script>
  </body>
</html>
fabrice
Mitglied

HELP: Embed a form in a React component

lösung

Still not working, I’m hacking it as @Alena did but it is really gross. Can you please provide a solution for this? Thanks

0 Upvotes
3PETE
HubSpot Employee
HubSpot Employee

HELP: Embed a form in a React component

lösung

@Alena and @fabrice

I just spun something up really quickly. Here is my code so I hope this helps. You can’t unfortunately use script tags in a render function as noted above. Let me know if this solves your problem or not. The first part calls the HubSpot script from our servers and the second part will then use the contents of said script to place the form in your component. I had to use a later lifecylce stage to get it to work. I was hoping it would have worked with componentDidMount(){} but it seemed to be firing to fast before the WillMount() could full finish loading the script.

export default class Foo extends Component {
componentWillMount(){

const script = document.createElement("script");


    script.src = "https://js.hsforms.net/forms/v2.js";
    script.async = true;

document.body.appendChild(script);


  }
  componentDidUpdate(){
    //you will need to change the below to match your portal ID and your form ID
     hbspt.forms.create({ 
     portalId: '2323210',
     formId: 'd8232cf6-b9ed-4abc-a81e-585801849cea'
   });
  }
  render() {

…Your Render code below

0 Upvotes
Nicht anwendbar

HELP: Embed a form in a React component

lösung

I am new to react …but How should we use the render function in that case?
Basically what should be inserted in the render method so that it get the information from the componentDidUpdate method?

0 Upvotes
Alena
Mitglied

HELP: Embed a form in a React component

lösung

Hi @pmanca !

Thanks for that. I implemented it as per your instructions but unfortunately that still doesn’t work. It throws the error that hbspt doesn’t exist, when this runs as the library is probably not fully loaded yet when I’m calling the forms.create function.

I’ve solved it by hardcoding the first script part where the library is loaded onto my root HTML (in Rails) and then moving the function call into the componentDidMount.

Works for me although it feels dirty… :smiley:

0 Upvotes
Alena
Mitglied

HELP: Embed a form in a React component

lösung

Did you ever solve this problem? I’m encountering the same issue now and don’t know how to fix it…

0 Upvotes