Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use third-party embed code in a React component

I need to use a third part embed code for a form. I'm trying to return it in a component, but it's obviously not working. How can I set this one up?

class Form extends Component {

  render() {

    return (
      <div>
        <div id="apply_form">
          <a name="form" id="formAnchor"></a>
          <script type="text/javascript" src="https://fs22.formsite.com/include/form/embedManager.js?1605047845"></script>
          <script type="text/javascript">
          EmbedManager.embed({
            key: "key",
            width: "100%",
            mobileResponsive: true
          });
          </script>
        </div>
      </div>
    );
  }
}

export default Form;
like image 607
Max T Avatar asked Dec 05 '16 21:12

Max T


People also ask

How do I load a third party script in React?

We start by creating an empty <script></script> tag in the memory as script and then assign the necessary attributes to its src and the id to identify the script later. Finally, we append the script to our <body></body> tag to actually load this.

Is it possible to integrate third party libraries with React?

Third-party libraries can be integrated with class components, also with functional components using Hooks. According to Dan Abramov, they (React Team in Facebook) have no plans to remove ES6 class syntax support in the future.

How do I import an external js file into ReactJS component?

Installation: Open a terminal inside your ReactJS project folder and write the following code to install react-script-tag Package. Import 'ScriptTag' component: Import the built-in 'ScriptTag' component from the react-script-tag library at the top of the file where we want to add the script tag.


1 Answers

Unfortunately, there's not a really clean way of doing this, short of reaching into the DOM to insert the external script, then running the embed code directly.

Here's how I'd go about this:

class Form extends Component {

  componentDidMount() {
    const script = document.createElement('script');
    script.setAttribute(
      'src', 
      'https://fs22.formsite.com/include/form/embedManager.js?1605047845');
    script.addEventListener('load', () => {
      EmbedManager.embed({
        key: "key",
        width: "100%",
        mobileResponsive: true
      });
    });
    document.body.appendChild(script);
  }

  render() {
    return (
      <div>
        <div id="apply_form">
          <a name="form" id="formAnchor"></a>
        </div>
      </div>
    );
  }
}

export default Form;
like image 74
Jacob Avatar answered Oct 27 '22 22:10

Jacob