I'm still a beginner in Nextjs, trying to implement a simple javascript like:
document.addEventListener("scroll", function () {console.log("scroll!")})
how to add the function in a local file and then load it with <script/>
in nextjs ?
P.S: i made a .js file with the function inside inside the project folder and tried to load it with next Script component but it gives me this error: Failed to load resource: the server responded with a status of 404 (Not Found)
CodePudding user response:
Next.js works with Modulation system.
If you want to add this function in some file, you need to export this function.
The code of the external file, let's call it "externalFile.js"
export function addScrollEventListener() {
document.addEventListener("scroll", function () {console.log("scroll!")})
}
Then when you want to use it in your component, you need to import it.
import { addScrollEventListener } from './externalFile';
In the useEffect hook ( which executes after mounting ), you can use it.
useEffect(() => { addScrollEventListener() }, [] )