Is there an alternative approach for implementing useEffect in Next.js?

Recently, I created a React code that displays a neon line from the top to the bottom of the page when scrolling. However, when I attempted to use this code in Next.js, it didn't work and I encountered an error stating "neonLine is null". Any ideas on why this is happening?

Below is the code snippet:

import React, { useState, useEffect } from "react";
import styles from "./Neon.module.css";

const Neon = () => {
  const [scrolling, setScrolling] = useState(false);
  
  useEffect(() => {
    const handleScroll = () => {
      setScrolling(true);
      const neonLine = document.querySelector(".nLine");
      const scrollTop = window.scrollY;
      const windowHeight = window.innerHeight;
      const documentHeight = document.documentElement.scrollHeight;
      const scrollPercentage = (scrollTop / (documentHeight - windowHeight)) * 100;
      neonLine.style.height = scrollPercentage + "%";
    };

    let scrollingTimeout;

    const checkScrollStop = () => {
      if (scrolling) {
        setScrolling(false);
        clearTimeout(scrollingTimeout);
      } else {
        const neonLine = document.querySelector(".nLine");
        neonLine.style.transition = "height 0.5s ease-in-out";
      }
    };

    window.addEventListener("scroll", handleScroll);
    window.addEventListener("scroll", checkScrollStop);

    return () => {
      window.removeEventListener("scroll", handleScroll);
      window.removeEventListener("scroll", checkScrollStop);
    };
  }, []);

  return (
    <div className={styles.con}>
      <div className={styles.neon}></div>
      <div className={styles.line}>
        <div className={styles["nLine"]}></div>
      </div>
    </div>
  );
};

export default Neon;

Answer №1

You currently have the following:

className={styles["nLine"]}

and

const neonLine = document.querySelector(".nLine");

Your assumption is that the value of styles["nLine"] will always be "nLine".

This assumption is incorrect because class names are randomized for uniqueness. This allows you to use the same name in different components without conflicts and having styles from other components applied.


It's generally recommended to avoid direct DOM access. Instead, use a reference when you need to access the DOM, rather than searching through the entire DOM tree.


const ref = useRef(null);
  useEffect(() => {
    const handleScroll = () => {
      setScrolling(true);
      const neonLine = ref.current;
...
    <div ref={ref} className={styles["nLine"]}></div>

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

What's the issue with my jQuery AJAX script?

I am experiencing an issue with my ajax pages using jQuery to retrieve content. Only one page seems to be working properly, even though I have multiple pages set up. How can I resolve this problem? $(document).ready(function() { $('.lazy_content& ...

Tips on getting the bot to react to a single "event" mentioned in the sentence, without multiple occurrences

Things are a bit complicated, but here's an example to illustrate: I've set up this event: client.on('message', async message => { if (message.content.toLowerCase().includes("megumin")) { message.channel.send("W ...

Tips for changing ES lint rules in a specific file within a React application

Currently, I am incorporating some older code into my React application. Webpack is generating numerous errors related to "no-restricted-globals" and "no-undef," which is preventing successful compilation. I am interested in finding a way to bypass this f ...

Creating a Custom FlatList Content Container with React Native

Is it possible to customize FlatList items with a custom component? I want to create a setup where my FlatList items are encapsulated within a custom component similar to the following: <ScrollView pt={8} px={16} pb={128} > <Card e ...

Tips on how to interact with a hyperlink in Python using a Selenium driver even when the content within the anchor tag is unknown

Utilizing a combination of selenium, phantomJS, and scrapy to scrape javascript content has proven to be an effective method. However, I am encountering an issue where I need to click on a link within a table after the javascript content has loaded. The ch ...

I'm keen on creating a marquee animation using Tailwind and Next.js

I'm working on creating a marquee animation using Tailwind CSS and Next.js, and I've made some progress. However, the issue I'm facing is that the items are not displaying one after the other smoothly; there seems to be a delay when the seco ...

Configuring environment variables during Jest execution

A variable is defined in my `main.ts` file like this: const mockMode = process.env.MOCK_MODE; When I create a test and set the variable to true, it doesn't reflect as `'true'` in the main file, but as `'false'` instead. describe ...

Retrieve the script's location from the server prior to the initialization of Angular

Is there a way to dynamically add a script in the index.html page based on the application version? I have a controller that retrieves the app version and attempted to achieve this using AngularJS: var resourceLoader = angular.module('MyTabs&apo ...

Pattern to identify a JSON string with Regular Expressions

Currently, I am working on developing a JSON validator from the ground up and have hit a roadblock when it comes to the string component. My original plan was to create a regex pattern that aligns with the sequence specified on JSON.org: https://i.sstatic ...

When trying to insert a string variable using Node and mysql, the operation fails

My attempt to add a string variable into the database is causing an issue. The boolean and integer values insert without any problems, but I keep receiving the following error message: Error: column "spike" does not exist (The value "spike" corresponds ...

Creating a specific type of table using Ruby on Rails

Is it feasible to create a table with two columns, where the left column incorporates multiple rows with a scroll bar, and the right column contains a large box housing buttons that alter based on the selection of blocks in the left column? ...

mention colleague(parent) instruction request

I have been exploring the use of metadata for setting HTML input attributes. After reading through the Attribute Directives Guide (https://angular.io/docs/ts/latest/guide/attribute-directives.html), I have developed the following implementation: import "r ...

Animate the service item with jQuery using slide toggle effect

Currently, I am working on a jQuery slide toggle functionality that involves clicking an item in one ul to toggle down the corresponding item in another ul. However, I am encountering difficulties in linking the click event to the correct id and toggling t ...

Troubleshooting the AutoHeight Problem in Slidesjs

My issue revolves around Slidesjs which can be found at . Specifically, I am facing a problem with autoHeight feature not displaying properly in Chrome. Initially, the height of slides shows as 0px but upon clicking to the next slide, it adjusts to the c ...

Displaying elements upon clicking using Javascript

I am in the process of achieving this task without Jquery. My goal is to display a div when triggering an event. Currently, I have the following code to hide the element: document.getElementById('element').style.display = 'none'; Her ...

Even when only a handful of modules are utilized, Webpack still imports a significantly large existing chunk

Currently, I am working on enhancing the splitChunks configuration in a multi-page application that utilizes Webpack 5, with a PHP backend and a Vue frontend. To optimize the vendor file size, I have started customizing the test function of the vendor cac ...

Utilizing Angular to make API requests and handle promises

Currently, I am facing a challenge in my angular application which involves working with the soundcloud api. The issue arises when I make a call to the soundcloud api to retrieve my tracks, loop through them to extract the iframe embed object, inject it in ...

Adjust the size of the text and the textarea at the same time

I am trying to resize text simultaneously while resizing the textarea in my code. I am using jQuery for this functionality. However, I believe there is an issue with the click function being separated. Any advice on how to fix this would be greatly appreci ...

When utilizing styled-jsx alongside postcss, experiencing issues with styles failing to reload or rebuild

I'm currently using postcss in conjunction with styled-jsx. In my setup, I have multiple CSS files that I'm importing using the @import directive within the _app.js file. Everything seems to work smoothly, except when I modify any of the CSS file ...

Efficient - Managing numerous database connections

I am currently working on a project using node.js and I have created a login form where users need to select the database they want to connect to. However, I am uncertain about how to establish a connection with the selected database. Is there a way for m ...