How can I apply and delete a css class only while scrolling in a React application?

Currently, I am designing a pretend blog layout to showcase my work. The grid of posts features cards that are precisely 400x400 in size with a hover effect that magnifies and adds a drop shadow (this is visible in the dashboard route).

However, an issue arises when scrolling through the page as the cursor tends to get stuck on the cards, halting the scroll functionality during the animation. While researching a solution, I stumbled upon an article () which discusses the performance advantages of disabling pointer events to the body while scrolling. Unfortunately, I am having trouble implementing this concept in React.

Is there a way to apply a class to the document body only while scrolling in React and remove it once the scrolling ceases? Possibly using a setTimeout method? I fear that such an approach might be inelegant...

I have provided the code where I intend to integrate this behavior. Although uncertain if it will provide clarity, the existing scroll event setup is designed to maintain page position as the navbar extends.

export default class Layout extends Component {
  // Code snippet here
}

As an attempt to resolve this, I experimented with setting

document.body.style.pointerEvents = 'auto'
in the componentDidMount() method and then disabling it within handleScrollY(). However, this approach proved ineffective since the pointer events were not restored post-scroll event. Similarly, I tested placing the logic in componentDidUpdate(), but encountered issues since no component was updating while the scrolling event wasn't active.

Answer №1

Here is a method to toggle a CSS class:

componentWillUnmount() {
  document.removeEventListener('scroll');
}
componentDidMount() {
  document.addEventListener('scroll', (event) => {
    const that = this;
    if (!that.state.isScrolling) {
      that.setState({ isScrolling: true });
      setTimeout(() => {
        that.setState({ isScrolling: false });
      }, 300);
    }
  });
}

You can then use the state or props to toggle the className

In your JSX, it would look something like this:

return (
  <div className={`class1 class2 class99 ${this.state.isScrolling ? 'scrolling' : 'not-scrolling'}`} >Content</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

Add a fresh item to a list using jQuery

Attempting to add a new list item using jQuery. In this scenario, the process works well, but when attempting to retrieve the value of an input field using .val(), no list item is created. http://www.example.com Code snippet: $(document).ready(functi ...

HTML - Customizing container with background color and ensuring minimum height of 100%

After creating a dynamic page using Bootstrap, I managed to add a sticky nav bar and footer. The navbar, footer, and page content are all in black color. I want the main content area to be white with black sides matching the background. Currently, I ca ...

Deciphering the '$' symbol in the Cheerio API

I'm feeling a bit confused about the significance of using the $ sign in the Node.js Cheerio API. Take for instance the snippet of code below: if(!error){ var $ = cheerio.load(html); var title, release, rating; var json = { title : "", ...

The image remains unchanged in the JavaScript function

My attempt to swap images using jQuery has hit a snag. Upon running the page, it appears that the chase() method finishes executing before the animation has completed. The goal was to create an illusion of chasing between two images by repeatedly replaci ...

Innovative way to design a menu using HTML, CSS, and JavaScript that dynamically resizes to a specific width

I'm currently working on a website and I'm trying to create a menu with specific width of 700px. However, I'm unsure whether to tackle this using CSS, JavaScript, or a combination of both. Which approach would be the most straightforward for ...

In my current Next.js project, I tried setting up a new [collectionId].jsx file within the pages directory, but I am facing issues with getting

In my current next.js project, I recently created a file named [collectionId].jsx within the pages directory. Interestingly, I noticed that Tailwind CSS does not seem to work properly with this file. However, when I renamed the file to [collectionId].js wi ...

Error: Uncaught ReferenceError: d3 is undefined. The script is not properly referenced

Entering the world of web development, I usually find solutions on Stack Overflow. However, this time I'm facing a challenge. I am using Firefox 32 with Firebug as my debugger. The webpage I have locally runs with the following HTML Code <!DOCTYP ...

Generating a client-side MD5 hash for an image file in order to compare it to the hash calculated by Firebase?

Is there a way to calculate the MD5 of an image file on the client side within my Angular Map application, that will match the MD5 when I store the file on Firestore? I need to verify that a user's file matches a reference version stored in Firebase ...

I am facing an issue where reducing the size of the renderer is causing my click events to be offset. What steps can I

At the moment, my rendered model (which is grey in color) stretches across the entire width of the html page with the mesh centered within that width. I want to reduce this width but when I do so, the click event on the model seems to be misaligned. Three. ...

Unusual trait of TrackballControls.target within the world of Three.js

My current project involves simulating a 3D distribution of galaxies. In this simulation, the galaxies are represented as points. question1.htm references galaxydata1.txt to calculate and load the galaxy positions: rawFile.open("GET", "galaxydata1.txt", ...

Exclude the data key from form submission based on condition in React

Is it possible to omit the onSubmit value if a checkbox is selected, without requiring a specific label/input? For example, when the indefinite runTime box is checked, the key runTimeSeconds doesn't need to be included in the payload. Can this logic b ...

Why is TypeScript resorting to using 'any' for specific prop type definitions in React?

Having some trouble with my props typing: export interface ITouchable { isDisabled?: boolean; margin?: Margin; height?: number; bgColor?: string; } The definition of Margin is as follows: type Margin = | { top?: number; bottom?: nu ...

Implement a feature in JSP that allows users to dynamically add or remove fields before submitting the data to the database

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http- ...

What are the best practices for properly deploying a React Vite project in production mode?

Currently, I am utilizing Vite alongside React and my aim is to deploy the project in production mode on a server. Below is the content of my vite.config.js file: export default defineConfig({ esbuild: { loader: "jsx", }, optimizeDeps: ...

Creating a dynamic select input in React that displays a default value based on other user inputs

My dilemma involves working with two radio buttons, named radio1 and radio2, along with a select input. The options available in the select input are conditional based on the selected radio button. I am aiming to automatically set the value of the select t ...

Add unique styles to a jQuery-included HTML document

I'm attempting to use jQuery to load an HTML page into the main body of another page. Specifically, I have a div called sidebar_menu positioned in the middle of the page, and I am loading content at the bottom using jQuery. $("#sidebar_menu").load(" ...

How to access the current class in Sass without referencing the parent class

.site-header .basket position: relative &-container width: 100% padding: 0 18px $basket: & &.opened #{$basket}-link border: 1px solid #e5e5e5 ...

Exploring the Power of GraphQL Args in Mutation Operations

Currently, I am in the process of developing a blog service using express and apollo-express in conjunction with mongodb (mongoose). While implementing mutation queries, I have encountered difficulties in accessing the arguments of a mutation query. I am ...

The <el-dropdown> function is currently facing a problem and is unavailable for use

While using Element-Plus, I've encountered an issue with the el-dropdown component. It doesn't display as a functional dropdown menu when imported into my project. Below is the code snippet I have used: <template> <div> <el- ...

Experimenting with a sample post on a minimalist Node.js application using Mocha and Superagent

I trust you are having a splendid day. Currently, I am focusing on enhancing my TDD skills in Node.js. To practice, I have developed a minimalistic application that handles basic GET and POST requests. The app simply displays a straightforward form to the ...