0

I'm trying to make this script for this service (http://luckyorange.com/) into a component. You are supposed to put it into index.html on public, but that seems insecure. I'm wondering if this can even be done.

        <script type='text/javascript'>
          window.__lo_site_id = 123456;

          (function() {
            var wa = document.createElement('script'); wa.type = 'text/javascript'; wa.async = true;
            wa.src = 'https://d10lpsik1i8c69.cloudfront.net/w.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(wa, s);
            })();
          </script>

I tried to do something like the solution to: Adding script tag to React/JSX but this seems to only work for scripts that are simple without anything between the script tags.

For example, Putting this into App.jsx:

export default function LuckyOrange(props) {
  React.useEffect(() => {
    window.__lo_site_id = process.env.REACT_APP_LUCKY_ORANGE_API_KEY;
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;

    script.src = `https://d10lpsik1i8c69.cloudfront.net/w.js`;
    const s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(script, s);

    document.body.appendChild(script);

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

doesn't work. What could I be doing wrong?

name
  • 29
  • 4
  • What is the error? Why are you removing the script: `document.body.removeChild(script);`? And you've already inserted it, no reason to append it to the body. Also, set `async` to false. Try: `return(
    )`, as body is not yet available to component when appending. You may need to use `useRef()`
    – GAEfan Aug 12 '20 at 23:47

1 Answers1

0

Why not just use:

return (
    <div>
    <script src="https://d10lpsik1i8c69.cloudfront.net/w.js" />
    <script>
        doStuff();
    </script>
    ....
    </div>
);
GAEfan
  • 11,244
  • 2
  • 17
  • 33