When utilizing both addEventListener("scroll", function()) and useState in React, there seems to be a lack of transition effects

Is there a way for me to smoothly transition the background color of my navigation, similar to this example?
Article.js

import React, { useRef, useEffect } from 'react';
import Grid from '@mui/material/Grid';
import { Link as RouterLink } from "react-router-dom";
import Typography from '@mui/material/Typography';
import Breadcrumbs from '@mui/material/Breadcrumbs';
import Link from '@mui/material/Link';
import './Article.css';


export default function Article() {
  const [isScrolling, setScrolling] = React.useState(false);

  useEffect(() => {
    function handleScroll() {
      if (window.scrollY < 10) {
        setScrolling(false);
      } else {
        setScrolling(true);
      }
    }
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, [isScrolling]);

  function CreateBasicBreadcrumbs() {
    return (
      <div
        role="presentation"
        className={`pop-up ${isScrolling && 'active'}`}
      >
        <Breadcrumbs
          aria-label="breadcrumb"
          sx={{ marginLeft: 2, }}
        >
          <Link
            underline="hover"
            color="inherit"
            component={RouterLink}
            to={'/'}
          >
            Home
          </Link>
          <Typography color="text.primary">
            Articles
          </Typography>
        </Breadcrumbs>
      </div >
    );
  }

  return (
    <Grid
      container='true'
      direction='row'
      width='100%'
      sx={{
        paddingTop: 5,
        backgroundColor: 'rgb(248, 249, 250)'
      }}
      onScroll={(e) => { console.log('scrolling') }}
    >
      <Grid
        item='true'
        xs={12}
        sm={12}
        md={12}
        lg={9}
        xl={7}
        sx={{
          paddingLeft: 5,
          height: '2000px',
        }}
      >
        <CreateBasicBreadcrumbs />
      </Grid>
    </Grid>
  );
}

Article.css

.pop-up {
  padding-bottom: 20px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  position: sticky;
  top: 10px;
  transition: all 1s linear;
}

.pop-up.active {
  background-color: rgb(255, 255, 255);
}

Whenever I run this code, the 'active' class is applied to the [div] element, but the background color changes abruptly from rgb(248, 249, 250) to rgb(255, 255, 255).
I suspect that the addEventListener updates isScrolling with every scroll, causing a re-render of the [div] element and its children. Can you help me identify what might be going wrong here?

Answer №1

Avoid nesting the Component called CreateBasicBreadcrumbs within another component. This can cause React to treat it as a new object every time Article is rendered, resulting in CreateBasicBreadcrumbs being unmounted and losing its state with each rerender of Article.

To prevent this, define CreateBasicBreadcrumbs outside of Article and pass down the prop isScrolling to it.

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

Automatically reduce the size of Java Script files and CSS files with compression

I'm currently working with Google App Engine and JQuery. I'm looking for a solution that can automatically compress my JavaScript and CSS files when deploying them to the GAE server. It's quite cumbersome to manually compress all the files e ...

Is there a way to wait for the state to be set without it returning a promise?

I'm having issues setting state with my setStockInfo hook and waiting for it to be fully set before running props.onInitialSet(). I attempted to use setStockInfo as a dependency in the useEffect, but it's not working. I require the data from stoc ...

Which one to use: AngularJs ui-router $location or $state?

Is there a way to convert the following code snippet: $location.path('/app/home/' + id).search({x:y}); into this: $state.go('/app/home/' + id).search({x:y}); I've attempted to make the switch, but I'm struggling to find e ...

Prevent the action icon for Chip from being enabled in Material-UI

I'm looking to remove the (x) option for each chip, without disabling the entire component. Implementing disabled property disables the whole component. https://i.stack.imgur.com/wQGJY.png Any ideas on how I can achieve this? Following Paven's ...

If the item is currently in the array of strings, remove it; otherwise, add it (according to M

Here is the mongoose schema I am working with: const userSchema = new mongoose.Schema({ username: String, password: String, solved: [{type: String}] }) I am attempting to achieve a specific functionality where if a query is present in the "sol ...

Substitute text while you input

Looking to generate a web-friendly image name based on user input from a form. Need to automatically replace spaces in the user's input with dashes as they type. The current code only replaces the first space encountered. How can I modify it to repl ...

Attempting to deactivate expired cards

Hello everyone, I could really use some assistance. I am trying to map items with a specific property called 'expired' and I want each card to render in a disabled state. However, I'm struggling to achieve this using MUI components. Here is ...

Sequential queuing of transitions in CSS3

Is it possible to queue CSS transitions with the same properties? My goal is to translate an element to a specific position (with a transition duration of 0) before translating it again. For example, in this mockup, clicking "move" should move the box 100 ...

jQuery for Revealing or Concealing Combinations of Divs

UPDATE: Check out this answer. I have a complex query related to jQuery/JavaScript. I came across a post dealing with a similar issue here, but my code structure is different as it does not involve raw HTML or anchor tags. Essentially, I am working on ...

Protractor encounters an error stating "No element found with specified locator" after attempting to switch to an

I've been attempting to download an embedded PDF from a webpage using Protractor selenium. However, I seem to be stuck when it comes to actually downloading the file as I always encounter the following error: Failed: No element found using locator: ...

What is the best method for sending an angularjs $http POST request when a user refreshes a page?

controller: app.run(function ($rootScope, $templateCache) { $rootScope.$on('$viewContentLoaded', function ($scope, $http) { $templateCache.removeAll(); alert("refreshing....."); $http({ url: '/an ...

Acquire Table Element Using Javascript

I have a HTML table that contains information such as names, addresses, and phone numbers. Within each row of the table, there is a link that can be clicked to open a popover. When a popover is opened, I want to save the name from that particular row. The ...

I'm struggling with my project called "Number TSP" and I can't seem to figure out why it's not working properly

Upon reaching the end of my code, I am encountering an issue where instead of seeing the expected output of "Done!", it displays undefined. This is the code in question: const container = document.querySelector(".container") const table = document.querySe ...

Retrieve a variable from list using FreeMarker within a loop that is chosen from a table

When clicking on the edit or delete anchor, I am trying to obtain the variable department.id for the selected department. I have attempted using <#assgn departmentId = "${department.id}">, but it retrieves the last id from the table as it i ...

What could be causing my image to not load on my HTML page?

Why is the first image loading correctly but the second one isn't appearing? <p>Please insert an image from a random website:</p> <img src="https://www.w3schools.com/images/lamp.jpg" alt="Lamp" width="32" h ...

Is there a way to stack one element on top of another without obstructing the links of the element in the back?

I am struggling with a problem and need some guidance. I can think of a solution where I reduce the width of the top element to avoid covering up the link, but I want to explore other possibilities. The challenge at hand is how to place a navigation bar o ...

Encountering an Unexpected Token Import Issue with Page Objects in Webdriver.io and Node.js

Hi, I've encountered an issue while attempting to run my test scripts using Node.JS and Webdriver.io. Everything was functioning correctly until I decided to implement the Page Object Pattern. I am now receiving an error in the console output: ERROR: ...

Adding a class to a Vue component using the $refs property

I am facing an issue where I need to add dynamic class names to various Vue components based on their reference names listed in a configuration file. Manually adding classes to each component is not feasible due to the large number of components. To addre ...

Factorizing a prefixed parameter using Express

My Express router has multiple routes: router .post('/:id/foo/*', func1) .get('/:id/bar/*', func2) .post('/:id/foobar/*', func3); All these routes have a common "/:id/" prefix and I am looking for a more concise and elegant ...

What is causing the unexpected token "<" error in the JSON at position 0 when using the delete method?

Encountering issues when attempting to delete data, The process works smoothly in Postman, but errors are arising in the browser: DELETE http://localhost:5000/items/[object%20Object] 404 (Not Found) Uncaught (in promise) SyntaxError: Unexpected token < ...