BPowers
BPowers

Reputation: 47

Trying to set a custom ID on a Hubspot form in Gatsby

I'm able to get a Hubspot form working as a component in Gatsby, but I would like to be able to set the formId per page. I've tried setting props in my component but haven't been successful. Here is an example of a page with the form working, and the code is below, with my portal id removed.

import React from "react";

class HubspotBrochureDownload extends React.Component {
  componentDidMount() {
    const script = document.createElement("script");
    script.src = "https://js.hsforms.net/forms/v2.js";
    document.body.appendChild(script);

    script.addEventListener("load", () => {
      if (window.hbspt) {
        window.hbspt.forms.create({
          portalId: "XXXXXX",
          formId: "1152aa7a-835d-410d-9462-08e2ddd226d8",
          target: "#hubspotForm"
        });
      }
    });
  }

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

export default HubspotBrochureDownload;

I have tried removing my formID and putting props. I found this example of componentDidUpdate but haven't had any luck

Upvotes: 2

Views: 811

Answers (1)

Sujith
Sujith

Reputation: 442

You can pass props so that the form accepts different id's. The prop passed inside componentDidMount(props), should know that the prop is inside that particular context in order get it value, so what you can do is use, this.props inside componentDidMount(props) scope. Here is the solution that I have found:-

import React from "react";

class HubspotBrochureDownload extends React.Component {
  componentDidMount(props) {
    const script = document.createElement("script");
    script.src = "https://js.hsforms.net/forms/v2.js";
    document.body.appendChild(script);

    script.addEventListener("load", () => {
      if (window.hbspt) {
        window.hbspt.forms.create({
          portalId: `${this.props.portalID}`,
          formId: "1152aa7a-835d-410d-9462-08e2ddd226d8", //also you can do fromID: `${this.props.formID}`
          target: "#hubspotForm"
        });
      }
    });
  }

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

export default HubspotBrochureDownload;

And import it in another file

import HubspotBrochureDownload from '../components/hubspot';

const MyComponent = props => {

 <HubspotBrochureDownload portalID="xxxxx" />
  // rest of your component
}

Upvotes: 1

Related Questions