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:


 import React from "react";
    import ReactDOM from "react-dom";
    import { Helmet } from "react-helmet";
    import "./styles.css";
    function App() {
      return (
        <div className="App">
            <script src="hello.js" type="text/jsx" />
          <h1>Hellok CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>

and ultra simple js script to include & run:


 console.log("opl882...") = "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:

       <script type="text/javascript">
         console.log("opl882..."); = "red"

it works!

Why doesn’t the external js file work?


You’ve made a typo here:

<script src="hello.js" type="text/jsx" />

The type is not JSX. In fact you can leave the type out altogether.

Given a file named hello.js in your static assets folder (that’s the public folder if you are using CRA), you can just do:

<script src="hello.js" />

And it should work as expected.

Oh friend I’ve been searching for the reason 2 days… The problem was that I’ve had the script in src CRA folder INSTEAD of the public
BIG thx for help:-)!
BTW - should the external scripts ALWAYS be in the public folder?

Yup, static assets should be added to the public folder, although normally you are encouraged to import them in JavaScript files instead (as you do with React Helmet).

You can read more here:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.