简体   繁体   中英

How integrate JS external resource in React project (Marketo)

I'm actually going deeper in React website but I've found really tough integrate external library code.

I'm actually handling Marketo code (that generate a FORM) and it gets three elements:

  • External file linked
  • Div with id for the Form
  • Script that write inside the DIV

  <script src="//app-sjst.marketo.com/js/forms2/js/forms2.js"></script> <form id="mktoForm_1057"></form> <script> MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function(form){ //Add an onSuccess handler form.onSuccess(function(values, followUpUrl){ //get the form's jQuery element and hide it form.getFormElem().hide(); //return false to prevent the submission handler from taking the lead to the follow up url. return false; }); }); </script> 

How can I properly integrate in a class in React without using HTML? I've written an idea but the url is not processed if injected with innerHTML. Here's what I've done:

 import React from 'react'; import PropTypes from 'prop-types'; const scriptMarketo = <script dangerouslySetInnerHTML={{ __html: ` MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057); console.log('test'); ` }} />; class MarketoForm extends React.Component { render() { return <div> <form id="mktoForm_1013"></form> {scriptMarketo} </div>; } } export default MarketoForm; 

Many thanks in advice!

Not sure if you are still stuck. Ran into a similar issue thought it might be helpful. The link Adding script tag to React/JSX in the comments is close, just needed to adjust things a bit to deal with Marketo

  class MarketoForm extends Component {
  /**
   * need to inject
   */
  componentDidMount() {
    const script = document.createElement('script');
    document.body.appendChild(script);
    // Depending on your lint, you may need this
    // eslint-disable-next-line no-undef
    MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057)
  }


  render() {
    return (
      <React.Fragment>
        <form id="mktoForm_1013"></form>
      </React.Fragment>
    )
  }
};

Some of this also depends on what type of state model you may be using. Not certain you want to re-render the Marketo form on a state update, so I am using componentDidMount

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