4

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?

6
  • Do you have any errors? Is the file found? Try changing the script type attribute from text/jsx to text/javascript. Commented Jan 9, 2022 at 22:15
  • @EmielZuurbier When I change to text/javascript I'm getting an error: "Unexpected token '<'"... Commented Jan 9, 2022 at 22:29
  • try keeping the text/javascript and changing the source to src={"./hello.js"} Commented Jan 9, 2022 at 22:43
  • @BilalAbraham Unfortunately changing the source to src={"./hello.js"} DOEN'T helped - still getting "Unexpected token '<'"... Commented Jan 9, 2022 at 23:01
  • @Daar44 I feel like you should just use my solution at this point Commented Jan 10, 2022 at 2:18

3 Answers 3

5

I usually do not implement .js files in react using a script tag. Instead you should import it at the top like this (assuming './hello.js' is the route to the file):

import './hello.js'

That file must also be located inside the src folder.

Sign up to request clarification or add additional context in comments.

6 Comments

Ok, friend this method DOES work but I'm still curious why my doesn't?
@Daar44 I dont think <script></script> tags work at all in jsx u always have to import as modules. Also if you wanted to send a value from a .js file you would simply write export default VARIABLE_TO_EXPORT
ok I'll accept and upvote but i/m still wondering why the solution with Helmet doesn't work!
@BilalAbraham react-helmet does support <script> tags.
@EmielZuurbier Thank you lol, I didnt even realize you were using react helmet, why does emiels text/javascript not work... after all the type of the file should not be text/jsx because that .js file has no jsx
|
1

I think the core issue you're probably seeing here is that hello.js is not accessible to the browser at the given URL. The src attribute in the <script> tag gives the URL for the browser to load the script from. Verify that you can directly access the script at the URL: it should just load as text in your browser to read if it's accessible.

The specifics of making a file directly accessible vary depending on your setup, but for a standard Create-React-App project (and a lot of others) there is a folder called public and you can put files you need to directly access by URL in there. To verify it's working, add your file there, then try to access it from the root of your app. If your app is running at localhost:3000 for instance, you can verify the file is accessible by navigating your browser to localhost:3000/hello.js. The file contents should appear in your browser as plain text. (Also, minor nitpick, I would use /hello.js as the src location, that feels like a less ambiguous URL to me.)

Once that's working, check out this StackOverflow over here to see about loading and running a vanilla JS file within React: Adding script tag to React/JSX . In your case, you're already using Helmet, so I think the code you already posted is mostly good to work, but the answers in that link should help troubleshoot. Although I think you want to change the type to text/javascript or just omit it entirely.

Finally, the reason the in-line JS works but not the referenced file is why I think it's about your browser not being able to find/access hello.js. The in-line JS just runs as it is because the JS is baked in. But to run it from a src, it has to find the source first, so if it can't find it at the URL you've given, it won't run. As for the other answer by Bilal here, that would work too, but it's depending on some sort of webpack magic or something to see it's a Javascript file, then pack it in such a way so that it runs. Nothing wrong with that necessarily, but you're basically offloading the creation of the <script> tag to whatever process interprets the import. (Also, note that if you're able to do import './hello.js', then your hello.js file must live in your overall src folder, so it's not publicly accessible, which means the script src is invisible from the browser's POV.)

Comments

0
useEffect(()=>{require('./paywell.js')},[])

1 Comment

It would be nice to give a brief explanation of how this works / how it solves the problem, and how it's different than existing answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.