0

I want to add a script file to a jsx element.

The script file contains a simple console.log('script ran') and nothing else (I want to add an actual script file, but for testing purpose I chose this minimal code).

// editor.js

console.log('script ran')
// App.jsx

import React, { useEffect } from 'react'

const App = () => {
  useEffect(() => {
    const script = document.createElement('script')
    script.src = '/editor.js'
    document.body.appendChild(script)
  }, [])

  return <></>
}

This throws the error below

Uncaught SyntaxError: Unexpected token '<' at editor.js 1:1

Folder Structure:

/
package.json
editor.js
src/
  App.js
  index.js

I have tried adding type="text/javascript", type="text/babel", async=true but nothing seems to work.

When I inspect the editor.js file in the developer tools, it shows an html file (The 404 page of my website)

When using type="text/babel" it doesnt throw any error, but also doesnt execute the script (console.log is never printed)

What am I doing wrong here? Also, I would like a solution which doesnt use React Helmet

React version: 17.0.1 (created with create-react-app)

0

1 Answer 1

6

You never serve the script and it's not accessible from the browser.

When you try to access /editor.js you are getting index.html, because that's how webpack's config for react works.

You should move your script to public

const App = () => {
  useEffect(() => {
    const script = document.createElement('script')
    script.src = process.env.PUBLIC_URL + '/editor.js'
    document.body.appendChild(script)

    // remember to remove the script
    return () => script.remove()
  }, [])

  return <></>
}

You didn't say anything about what development server you are using, but I guess it's create-react-app

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

3 Comments

while is this likely very true (and I've +1'ed it), the bigger question in my head is "why manually include an external script dynamically inside a component?". Can't you just import the relevant parts of it into your App.jsx and use them there?
Probably not the case this time, but it can be useful sometimes with self-embedding scripts like this one <script src="https://gist.github.com/KonradLinkowski/4dbaed1294a677d618c0b0ab03baf057.js"></script> codepen.io/KonradLinkowski/pen/VwxVQxz I guess
@RobinZigmond, right. It was a third-party script so I didn't know I can include it like that.

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.