How do I use/include third party libraries in react?

Viewed 31922

I would like to use jQuery and some other third party libraries not native to React. How can I use them in my React projects? I read componentDidMount is a good place to invoke third party libraries.

Unfortunately, I am unable to use the libraries as I keep getting " is not defined" errors even though I have properly linked script tags to those libraries in my index.html file.

2 Answers

I needed to use the third party libraries as well as custom written javascript files inside of a React Component without loading them across other routes.

Kindly note am use a React Hook i.e. useEffect() thus you need a version of react which supports them.

Below is what worked for me.

import React, { useEffect } from "react";

const Airstrip = props => {
  useEffect(() => {
    // Now Attach All Third Party Scripts.
    let threeJsScript = document.createElement("script");
    let orbitJsScript = document.createElement("script");
    let guiJsScript = document.createElement("script");
    let mainJsScript = document.createElement("script");

    // Hook Sources.
    threeJsScript.src = `${process.env.PUBLIC_URL}/js/three.js`;
    orbitJsScript.src = `${process.env.PUBLIC_URL}/js/orbit.js`;
    guiJsScript.src = `${process.env.PUBLIC_URL}/js/gui.js`;
    mainJsScript.src = `${process.env.PUBLIC_URL}/js/main.js`;

    // Persist order of Loading.
    threeJsScript.async = false;
    orbitJsScript.async = false;
    guiJsScript.async = false;
    mainJsScript.async = false;

    // Append to index.html
    document.body.appendChild(threeJsScript);
    document.body.appendChild(orbitJsScript);
    document.body.appendChild(guiJsScript);
    document.body.appendChild(mainJsScript);

    // Do Clean ups
    return () => {
      document.body.removeChild(threeJsScript);
      document.body.removeChild(orbitJsScript);
      document.body.removeChild(guiJsScript);
      document.body.removeChild(mainJsScript);
    };
  }, []);

  return (
    <div id="airstrip">
      <canvas
        id="canvas"
        onClick={() => {
          alert("Yeah");
        }}
      ></canvas>
    </div>
  );
};

export default Airstrip;
Related