How to use external js files in index.html React

Viewed 942

I am using an HTML template, which I converted to React by placing the assets folder into public (in React). I put the both the css files link and js scripts to public index.html (see code below). The css is displayed properly, however, the javascript functions aren't working. I tried installing jquery, but it still doesn't work.

I tried to put the js files into the src files and import it in the App.js file as: import './js/main.js'. This also doesn't work and logs errors such as: Expected an assignment or function call and instead saw an expression and 'jquery' is not defined.

Index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <link href="%PUBLIC_URL%/assets/css/main.css" rel="stylesheet">  
  <link href="%PUBLIC_URL%/assets/css/fontawesome-all.min.css" rel="stylesheet">  
  <link href="%PUBLIC_URL%/assets/css/noscript.css" rel="stylesheet"> 

    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>

    <!-- jQuery CDN - Slim version (=without AJAX) -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <!-- Popper.JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
    <!-- Bootstrap JS -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
    <script src="%PUBLIC_URL%/assets/js/jquery.min.js"></script>
    <script src="%PUBLIC_URL%/assets/js/jquery.scrollex.min.js"></script>
    <script src="%PUBLIC_URL%/assets/js/browser.min.js"></script>
    <script src="%PUBLIC_URL%/assets/js/breakpoints.min.js"></script>
    <script src="%PUBLIC_URL%/assets/js/util.js"></script>
    <script src="%PUBLIC_URL%/assets/js/main.js"></script>
  </body>
</html>

Does anyone know why the js files aren't working? Any help would be highly appreciated.

Thanks in advance!

1 Answers

Try to put your scripts inside index.html's head tag, or just use npm i jquery --save and then import $ from 'jquery'.

Related