简体   繁体   中英

Dynamic form only shown on refresh

I've been having an issue where the client has provided me a third party Marketo form to include on one of the pages I'm building out which works on a "normal" html page when testing locally, however on Gatsby, it's not working. The script that was provided is as follows:

<script src="//app-xxxx.marketo.com/js/forms2/js/forms2.min.js"></script>
<form id="mktoForm_xxxx"></form>
<script>MktoForms2.loadForm("//app-xxxx.marketo.com", "xxx-xxx-xxx", xxxx);</script>

I've added the top script tag into gatsby-ssr.js like so:

import React from 'react'

export const onRenderBody = ({ setPostBodyComponents }) => {
  setPostBodyComponents([
    <script
      key="mktoForm_test"
      src="//app-sjst.marketo.com/js/forms2/js/forms2.js"
    />,
    <script
      key="/js/site.js"
      src="/js/site.js"
    />
  ])

I've added the following to /static/js/site.js to initialize the form:

MktoForms2.loadForm("//app-xxx.marketo.com", "xxx-xxx-xxx", xxxx);

Then, on the page where I want the form, I've added this:

<form id="mktoForm_xxxx"></form>

The form only displays when I'm on the page and manually refresh the browser. Clicking into the page from any other page does not render the form at all. I'm guess it's how Gatsby/React routes to the page with the form.

Can someone please help??

You probably need to call that.loadForm function when the component that has that form mounts.

React.useEffect(() => {
// load form here...
}, []

If it's just being called in site.js, it's probably being called before the form element is present in the DOM so it has nothing to attach to.

I created this example a while ago, leaving it here in case it's extra help: https://github.com/CharlieDieter/react-marketo-hook

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM