APIs & Integrations

fabrice
Member

HELP: Embed a form in a React component

SOLVE

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 Accepted solutions
DHawkings
Solution
Member

HELP: Embed a form in a React component

SOLVE

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;

 

 

View solution in original post

EdCupaioli
Solution
Member

HELP: Embed a form in a React component

SOLVE

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. 

View solution in original post

DGomez2
Solution
Member

HELP: Embed a form in a React component

SOLVE

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 😃 

View solution in original post

15 Replies 15
DGomez2
Solution
Member

HELP: Embed a form in a React component

SOLVE

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 😃 

Not applicable

HELP: Embed a form in a React component

SOLVE

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
Solution
Member

HELP: Embed a form in a React component

SOLVE

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
Participant

HELP: Embed a form in a React component

SOLVE

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
Participant

HELP: Embed a form in a React component

SOLVE

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
Solution
Member

HELP: Embed a form in a React component

SOLVE

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
Member

HELP: Embed a form in a React component

SOLVE

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
Community Manager

HELP: Embed a form in a React component

SOLVE

Thanks for adding your solution, @EdCupaioli 🙌

— Jaycee

linkedin

Jaycee Lewis

Developer Community Manager

Community | HubSpot

0 Upvotes
aalstes
Participant

HELP: Embed a form in a React component

SOLVE

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

0 Upvotes
CaseyBinkley
Participant

HELP: Embed a form in a React component

SOLVE

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
Member

HELP: Embed a form in a React component

SOLVE

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

SOLVE

@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
Not applicable

HELP: Embed a form in a React component

SOLVE

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
Member

HELP: Embed a form in a React component

SOLVE

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
Member

HELP: Embed a form in a React component

SOLVE

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

0 Upvotes