DEV Community

Mulligan81
Mulligan81

Posted on

Adding external javascript script to React

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

and ultra simple js script to include & run:

hello.js:

console.log("opl882...")
document.body.style.backgroundColor = "red";
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

it works!

Why doesn't the external js file work?

Top comments (1)

Collapse
 
anesu profile image
Anesu Kafesu

Not sure why it doesn't work but I'd put the hello.js code in a function and export it from hello.js. Then import the function and call it from index.js.