Next.JS implement external ".js" with <script>

GijsHeg picture GijsHeg · Mar 14, 2019 · Viewed 9.6k times · Source

Im Building a website with Next.Js and I tried to implement an external .js file (Bootstrap.min.js & Popper.min.js) but it is not displayed. Im not sure what the problem is!

I implemented it like this:

It looks good to me? what am I missing, it's not projecting as it should!

When I tried a script inside the page it shows "Hello JavaScript" for a very short time and then it disappears?

<p id="demo"></p>
<script>document.getElementById("demo").innerHTML = "Hello JavaScript";</script>

How do i fix it?

Please help!

Im Using: "next": "^8.0.3", "react": "^16.8.4", "react-dom": "^16.8.4"

Answer

GunnerFan picture GunnerFan · May 17, 2020
  1. You need to put all your scripts inside the Head tag.
  2. Don't put raw javascript inside the Head tag. Put it in a separate file and import the script in the Head tag

You can create a .js file, which contains your raw js code, in the public folder and then use the script in the Head tag. I am not sure why we have to do this, but this is how it works in Next.js

So for your problem, this will work:

public/js/myscript.js

document.getElementById("demo").innerHTML = "Hello JavaScript";

Layout.js

import Head from 'next/head';

const Layout = (props) => (
<div>
    <Head>
        {/* import external javascript */}
        <script type="text/javascript" src="..."></script>
        <script type="text/javascript" src="/js/myscript.js"></script>
    </Head>
    <p id="demo"></p>
</div>
);

export default Layout;