0

I have a project in which I am using a CDN to load a script. I load it via useEffect in my component directly. Simplified code:

React.useEffect(() => {
    const script = document.createElement('script');

    script.src = "https://cdn.cubing.net/js/cubing/twisty";
    script.type= "module";

    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    }
  }, []);

  return (
      <twisty-player>
      </twisty-player>
)

Twisty-player is the custom HTML tag that comes from the script (it is not a react component). The documentation for it is here: https://js.cubing.net/cubing/twisty/

I have a few questions:

  1. This code works for me, but I don't understand why, because we aren't awaiting anything. I render the twisty-player right after we load the script, but we aren't waiting for the script to finish downloading, so I'm not sure how we are able to render it.
  2. Is this the recommended way to add the script for the twisty-player? Is there a better way to do it?
  3. I tried to load the script directly into the HTML head, and then I removed my entire useEffect statement from my component, but this did not work, why is that?
713sean
  • 313
  • 11
  • It's hard to know why doing this conventionally isn't working for you because you haven't shared your code for that. Have a look at [this](https://stackoverflow.com/questions/807878/how-to-make-javascript-execute-after-page-load). – jmargolisvt Dec 09 '22 at 02:48

1 Answers1

0

If you trying using cubing/twisty on the ReactJs.

You can using cubing via npm by npm install cubing

Here is the simple way you can do this.

import { TwistyPlayer, TwistyPlayerConfig } from "cubing/twisty";
import React, { useEffect, useRef } from "react";

const renderTwistyPlayer = (config?: TwistyPlayerConfig) => {
  return new TwistyPlayer(config);
};

export default function Demo() {
  const twistyRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const twistyDom = twistyRef.current;
    if (twistyDom) {
      twistyDom.innerHTML = "";
      twistyDom.appendChild(
        renderTwistyPlayer({
          puzzle: "3x3x3",
          alg: "U' D B' L B' U' R F2 U R2 F' U2 R2 F2 R2 B D2 F' R2 L2 B2",
          background: "none",
        })
      );
    }

    return () => {
      twistyDom?.removeChild(twistyDom.firstChild as Node);
    };
  }, []);

  return <div ref={twistyRef}>Nothing</div>;
}

phamthainb
  • 23
  • 6