react-helmet icon indicating copy to clipboard operation
react-helmet copied to clipboard

Adding external javascript script to React failed!

Open Mulligan81 opened this issue 3 years ago • 1 comments

I'd like to include & run some js file in the React using Helmet component. Here is the simple code:

index.js:

import React from "react";
import ReactDOM from "react-dom";
import { Helmet } from "react-helmet";

import "./styles.css";

function App() {
  console.log("op");

  return (
    <div className="App">
      <Helmet>
        <script src="hello.js" type="text/jsx" />
      </Helmet>
      <h1>Hellok CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

and ultra simple js script to include & run:

hello.js:

console.log("opl882...")
document.body.style.backgroundColor = "red";

But the script seems NOT to work! - i have no console output and/or background color changed. What's odd when I use the js code as an inline code like:

 <Helmet>
   <script type="text/javascript">
     console.log("opl882..."); document.body.style.backgroundColor = "red"
   </script>
 </Helmet>

it works!

Why doesn't the external js file work?

Mulligan81 avatar Jan 10 '22 16:01 Mulligan81

Hi, @Mulligan81 ! For you resolve this problem, you can move the your project files(specifically the "hello.js") from "src" folder to "public" folder. You can move or copy ! Good Lucky !

MaxwellAt avatar Jul 27 '22 22:07 MaxwellAt