The proper way to implement global scripts in Next.js

I am currently working on implementing a global fade-in animation for all components in my application. By adding the className "fadeIn" to each element and setting the default opacity to 0, I then utilize JavaScript to change it to 1 when the element is visible.

Here is how I have approached this so far. While it does work initially, there is a significant issue that needs addressing. I suspect there may be better methods available, and I would greatly appreciate any suggestions.

The main problem I encounter is that the animation only functions on the initial render. If I navigate to another page and return, all elements are hidden with an opacity of 0, and the script fails to run.

Any guidance on remedying the existing issue or improving the implementation process would be invaluable.

_app.js

function MyApp({ Component, pageProps }) {

  return <Provider store={store}>
    <Layout>
      <PersistGate persistor={persistor}>
        <Component {...pageProps} />
      </PersistGate>
      <FadeIn />
    </Layout>
  </Provider>
}

export default MyApp

FadeIn component

import React, { useEffect, useState } from 'react'
import Script from 'next/script'
import ReactDOM from 'react-dom';

export default function FadeIn() {

  const myScript = (
    <Script src='/utils/scripts/appearOnScroll.js' strategy="afterInteractive" />
  )

  return ReactDOM.createPortal(myScript, document.getElementById('doc-root'));

}

appearOnScroll.js

(function () {
  const faders = document.querySelectorAll('.fade-in');
  const faderOptions = {
    threshold: 1
  };
  const appearOnScroll = new IntersectionObserver(function (
    entries,
    appearOnScroll
  ) {
    entries.forEach(entry => {
      if (!entry.isIntersecting) {
        return;
      } else {
        entry.target.classList.add('appear');
        appearOnScroll.unobserve(entry.target);
      }
    })
  }, faderOptions);

  faders.forEach(fader => {
    appearOnScroll.observe(fader);
  });
})();

Answer №1

One interesting thing about the _app component is that it does not refresh during page transitions, which means your script won't run again when navigating between pages.

For more information on customizing the app component, check out this link.

If you want to trigger some code when a page changes, you can use the router.events module from next/router:

Find out more about using router events here.

You may need to adjust your custom script to respond to route changes (the provided link offers various events to choose from based on your requirements).

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

Steps for implementing a conditional statement to handle an empty string in HTML

I need to figure out how to display a different message if my string is empty. Can anyone help me with this? <div class="padding" id="dealBorder"> <pre id="informationDealText"><pan class="inner-pre" style="font-size: 24px; color: whi ...

Formik React struggling with error management and handling tasks accurately

I am currently using the Formik template to develop a Login Form. onSubmit={( values, { setSubmitting, setErrors /* setValues and other goodies */ } ) => { props.logMeIn(va ...

Tips for turning on a gaming controller before using it

Current Situation In my ionic side menu app, I have a main controller called 'main view'. Each tab in the app has its own controller, which is a child of the main controller. The issue I'm facing is that when I start the app, the first cont ...

What is the reason in AngularJS for requiring directive attributes to be hyphen-separated while their scope variables are camelCased?

Here is an example in Html: <!-- Note 'display-when' is hyphenated --> <wait-cursor display-when="true"></wait-cursor> Then, when defining it in the directive: scope: { // Note 'displayWhen' is camelCased show: ...

Conflicting React Dependency Version 18.0 and Material-UI: A Compatibility Issue

I have attempted all the suggestions provided here, but unfortunately, none of them seem to work. I am encountering an issue with Material UI Icons npm installation which is causing me to be unable to resolve the dependency tree. Additionally, I am also fa ...

Ways to conceal the jqgrid thumbnail

I have a jqgrid that displays a large amount of dynamic data. I am looking for a way to hide the thumb of the vertical scrollbar in the jqgrid when scrolling using the mousewheel. Here is a basic example: var data = [ [48803, "DSK1", "", "02200220", "O ...

Experiencing an issue with mui/material grid causing errors

An error occurred in the file Grid2.js within node_modules/@mui/material/Unstable_Grid2. The export 'createGrid' (imported as 'createGrid2') could not be found in '@mui/system/Unstable_Grid' as the module has no exports. Desp ...

Struggling to get my React Typescript styled component slider to function within the component

Check out my demo here I created a simple react application using TypeScript and styled components. The main feature is a slider that adjusts the height of a red box. The red box is a styled component and I pass the height as a prop. Everything was fun ...

Creating a Standard DIV Element (JavaScript Code)

Just a quick question here. http://jsfiddle.net/fkling/TpF24/ In this given example, I am looking to have < div>Bar 1</div> open as default... Any suggestions on achieving that? That would be all for now. Thank you so much! :D The JS script: var ...

Angular 5 offers the ability to incorporate dynamic checkbox input into your application

Here is my code snippet: <input [type]="'checkbox'" [(ngModel)]="inputValue"> <p>Value: {{ inputValue }}</p> I'm puzzled as to why the value in inputValue remains unchanged. Can anyone shed light on this? I am unable to ...

sharing data between two node.js servers using http

I am currently working on integrating two node.js/express servers that communicate with each other using HTTP. One of the servers, known as server A, is responsible for handling file upload requests from the browser. My goal is to seamlessly transfer any u ...

Using jQuery to control mouseenter and mouseleave events to block child elements and magnify images

My objective is to create a hover effect for images within specific div elements. The images should enlarge when the user hovers their mouse over the respective div element. I plan to achieve this by adding a child element inside each div element. When the ...

Implement a personalized callback function for a specific resource

Currently, I am using angularjs version 1.1.5 and have a service provider for a resource. In one specific use case, the returned response needs to be reprocessed and some information normalized. Although this is a special case, the resource is utilized thr ...

What is the safest way to convert a local file path to a file:// URL in Node.js?

In my node.js application, I am faced with the task of converting local file paths into file:// urls. After some research, I came across the File URI scheme on Wikipedia and I believe that there must be a solution out there or perhaps even an npm module t ...

A Guide to Importing CSV Data Into a Datatable

Is there a way to efficiently import data from a CSV file and display it in a table using the datatables plugin? Currently, I have a fixed table structure: <table id="myTable" class="table table-striped" > <thead> ...

The expanding submenus within each menu are activated by a simple click

I am facing an issue with my menus and submenus. Whenever I click on a menu, all the associated submenus also open up. How can I make it so only the parent submenu opens? https://i.stack.imgur.com/7FDq3.png const [subMenu, setSubMenu] = useState(false) ...

Can we implement attribute selectors in Material-UI while utilizing makeStyles?

Is it possible to extract all the div elements with specific Mui class names such as access-MuiPickersCalendarHeader-switchHeader, access-MuiPickersDay-day? My components are styled using StylesProvider which adds "access" as a prefix to the original Mater ...

For optimal display on mobile devices, include "width=device-width" in the meta tag "viewport"

Is it necessary to include "width=device-width" in the meta tag named viewport when dealing with mobile phones? I've been attempting to make use of this, but without success: //iPhone Fix jQuery(document).ready(function(){ if (jQuery(window).widt ...

Angular 8: How to Retrieve Query Parameters from Request URL

Can I retrieve the GET URL Query String Parameters from a specific URL using my Angular Service? For example, let's say I have a URL = "http:localhost/?id=123&name=abc"; or URL = ""; // in my service.ts public myFunction(): Observale<any> ...

How should we provide the search query and options when using fuse.js in an Angular application?

Having previously utilized fuse.js in a JavaScript project, I am now navigating the world of Angular. Despite installing the necessary module for fuse.js, I'm encountering difficulties implementing its search functionality within an Angular environmen ...