0

I have a component which need to contain a form from Marketo.

In the backend, I have an ACF field called form_id. Idea being is that the user can input the Marketo form ID in the backend, and I will pass the value from that field into the <script> snippet in the component and it will find the relevant form.

Currently, I am trying to use react-helmet, however, it errors (TypeError: tag[primaryAttributeKey].toLowerCase is not a function) because of the field value from the backend.

Here is how the embed code appears from Marketo (with form ID 9999 used as an example):

<script src="//url.com/js/forms2/js/forms2.min.js"></script>
<form id="mktoForm_9999"></form>
<script>MktoForms2.loadForm("//url.com", "999-XXX-999", 9999);</script>

And here is my current approach trying to get the value from backend to appear in place of 9999:

import React from "react";
import { useStaticQuery, graphql } from "gatsby";
import parse from "html-react-parser";
import {Helmet} from "react-helmet";

const ContactHero = (props) => {
  return {
  
  <div className="contactHero__form">
    <Helmet>
      <script src="//url.com/js/forms2/js/forms2.min.js"></script>
      <form id={`mktoForm_${parse(form_id)}`}></form>
      <script>MktoForms2.loadForm("url.com", "999-XXX-999", {parse(form_id)})</script>
    </Helmet>
  </div>
  
  };
};
Freddy
  • 683
  • 4
  • 35
  • 114

1 Answers1

0

Unless there is a special case, it looks like you can just call MktoForms2.loadForm in component such as:

useEffect(() => {
    MktoForms2.loadForm("url.com", "999-XXX-999", parse(form_id));
}, [form_id]);

The useEffect will call its first parameter after the component has mounted, and the form is in the DOM. This way, the MktoForms2.loadForm function will be able to find the form. Without the useEffect the function will be called before the form is put onto the page by react and the function won't be able to find the form. The second parameter ([form_id]) to useEffect will call the function passed to useEffect whenever the form_id updates, or is initially passed to the component. You can import MktoForms2 from whatever script file you are including in you html.

If you really must put the MktoForms2.loadForm inside a script tag, you should use something like this, but it is easy to mess up react with script tags, especially if they edit the HTML document.

Ethan
  • 122
  • 10