Tips for integrating Basic Javascript into a Nextjs project

As a novice in Nextjs, I am attempting to incorporate a basic JavaScript function like this:

document.addEventListener("scroll", function () {console.log("scroll!")})

How can I add this function in a local file and then load it using <script/> in Nextjs?

P.S: I created a .js file with the function inside the project folder and attempted to load it using the next Script component, but encountered this error: Failed to load resource: the server responded with a status of 404 (Not Found)

Answer №1

Modulation system is fully compatible with Next.js.

To incorporate a specific function into a file, you must ensure that the function is exported.

Consider an external file named "externalFile.js"

export function addScrollEventListener() {
  document.addEventListener("scroll", function () {console.log("scroll!")})
}

Subsequently, when you wish to utilize it in your component, import it as follows:

import { addScrollEventListener } from './externalFile';

You can then employ it within the useEffect hook (which triggers post mounting):

useEffect(() => { addScrollEventListener() }, [] )

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing the Google Maps API into a React application to generate a customized route between two specified points

I'm currently developing a React application that is designed to display the distance between two points on a map. Although I successfully implemented this feature using JavaScript and HTML, I am facing challenges in converting it to React as I am re ...

Problems encountered with iframe-resizer in Next.js: Notification of GPLv3 License and Error message indicating "iFrame not responding"

My project in Next.js 14 involves creating a testimonial feature with testimonials displayed through an iframe. The aim is to generate an iframe tag (and potentially necessary script tags) that, when inserted into any website's HTML, allows users to v ...

Exploring the wonders of accessing POST request body in an Express server using TypeScript and Webpack

I am currently working on a Node and Express web server setup that utilizes Webpack, along with babel-loader and ts-loader. Let's take a look at some key portions of the code: webpack-config.js: const path = require("path"); const nodeExte ...

Reactjs implemented with Material UI and redux form framework, featuring a password toggle functionality without relying on hooks

Currently, I am working on a react project where I have developed a form framework that wraps Material-UI around Redux Form. If you want to check out the sandbox for this project, you can find it here: https://codesandbox.io/s/romantic-pasteur-nmw92 For ...

Toggle the visibility of all elements using jQuery by creating multiple buttons for each action

I have a group of 4 buttons that control the visibility of images on the page. Each button toggles between showing and hiding all images when clicked. When a button is clicked, it changes its text from "HIDE ALL" to "DISPLAY ALL." The issue I'm facin ...

Instructions for automatically scrolling an iframe down by 100px every 5 seconds

Is there a way to scroll an iframe down by 100px every 5 seconds using JavaScript or any other software? I am aware of the window.scrollTo(x,y); method for scrolling the window, but how can this be adapted for an iframe? The iframe in question is displayi ...

Getting Started with Parsing JSON Objects in ReactJS

In my ReactJS project, I am trying to parse through a JSON list using the following model: public class ModelEmployee { public List<Employeelist> Employees { get; set; } public int count { get; set; } public int Pagenumber { get; set; } ...

express.js - one handler to rule them all: managing multiple routes

Currently in the process of developing an application, I have a routes file structured as follows. const router = require('express').Router(); router.get('/', (req, res) => res.render('statics/home')); router.get('/j ...

Using JQuery to dynamically add a third expandable row to a table

In my JQuery code (within documentReady), I utilize DataTable to create a table. table = $('#transaction').DataTable({ "ajax": { "url": "servicingTransactionsLoad.do", "type": "GET", " ...

Populate an empty value in a key-value pair by using the subsequent value

Replace an empty value in a key-value pair with the first value of the next key. myitems = { 'items1': [{first:true, second:false}, {first:true, second:true}], 'items2': [], //should be filled with {first:true, second:false} 'it ...

Manipulating events through adjusting values of a JQuery-UI range-slider

My range-slider's values are being set with the code: $('...').slider( 'values', [ 0, 10000 ] );. However, I am facing an issue where this line triggers the change( event, ui ) event twice. Is there a way to ensure it only triggers ...

Creating real-time updates in Vuex and components using their data

There are two distinct elements here - a button and a form. By clicking the button, I can trigger an action in Vuex using "$store.dispatch". addWorkerSubmit: async function () { ... await this.$store.dispatch('workermanage/addWorkerSubmit ...

Is there a way to display a message box when the mouse cursor hovers over a text box?

Currently, I have set up 3 text boxes in my project. The functionality I am trying to achieve is when the user clicks on the second text box, the value of the first text box should be displayed in a message box (providing that the validation for the first ...

The Angular 2 bootstrap function is throwing an error stating that the argument type AppComponent cannot be assigned to the parameter type Type

Presenting my very first Angular 2 application with a simple Hello World example, inspired by the Angular 2 quick start guide. import {Component} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; @Component({ ...

Refreshing the page will cause the Next Auth session to expire

Currently, I am facing an issue with my MongoDB database and NextAuth authentication. The problem arises when the session persists even after logging out unless the page is reloaded. I have searched through various threads on GitHub but haven't found ...

Retrieve JSON data with a GET request and populate an array with the results before returning

Recently, I delved into using the mobile framework LungoJS. Although my experience with JavaScript is limited, I am determined to make changes to the following original code: ORIGINAL.JS var mock = function() { var mock = []; for (var i=1 ...

Script executing single run only

I'm currently working on a side menu that slides open and closed from the left with the press of a button. I have successfully implemented the CSS and HTML code, but I am facing issues with the JavaScript. The functionality works flawlessly at first: ...

Is there a way to display the tooltip at all times in Chart.js version 3.7.1?

https://i.sstatic.net/Lmfqn.png [Chart.js 3.7.1] Is there a way to keep the tooltip always visible? I am looking for a method to have the tooltip constantly displayed. Additionally, I would like the text to be darkened only on today's date. Si ...

Tips for fixing connection issues when trying to connect to MongoDB on AWS Cloud9

I've been following a tutorial from 'Web Dev Simplified' using the AWS-Cloud9 Ubuntu environment and everything was going smoothly until I encountered an issue while trying to connect to MongoDB. The database appeared to install correctly us ...

What is the process for implementing Next.js incremental static regeneration (ISR) with Docker deployment?

I am currently pondering the optimal approach for deploying a Next.js app on Docker. The Docker image needs to be deployed on two distinct environments: first on TEST and then, utilizing the same image, on PROD. Each environment is connected to its own dat ...