0

so I'm new to Next.js and I was wondering how to use onclick to call a function from an external file in my public folder.

Here is my index.js

import Head from "next/head"
import Script from "next/script"

export default function Home() {
  return (
    <div>
      <Head>
        <Script src="/hello.js"></Script>
      </Head>
      <p id="hi">Hello World</p>
      <button onclick="hello()">Click me</button>
    </div>
  )
}

Here is my hello.js

function hello() {
  document.getElementById("hi").innerHTML = "Hi World";
}

P.S. I will need to export it to static HTML so placing the javascript above the return function will not work.

SappyCS
  • 53
  • 5
  • Read the comment thread on this question: https://stackoverflow.com/questions/72305470/how-to-execute-this-javascript-code-in-react#comment127739835_72305470 – Quentin May 20 '22 at 09:00
  • I've been trying to solve this for 2 hours, I gave up that's why I'm asking here – SappyCS May 20 '22 at 09:08
  • Again, go and read that comment thread. Your entire approach is wrong. Forget about `innerHTML`. Forget about external scripts. Learn about modules, state and JSX. You're working in React now. – Quentin May 20 '22 at 09:13

1 Answers1

0

add

import hello from 'hello' 

also you need to export your function with export keyword:

export function hello() {
  document.getElementById("hi").innerHTML = "Hi World";
}
Voidy
  • 424
  • 3
  • 12