Adjust the background hue while scrolling (scrolling feature not functioning properly)

Seeking assistance with changing the background color of a component based on user scrolling behavior. I have attempted to achieve this using the following code snippet:

  const [mainColor, setMainColor] = useState('red')

  const listenScrollEvent = () => {
    window.scrollY < 10
      ? setMainColor('green')
      : setMainColor('red')
  }
  useEffect(() => {
    window.addEventListener('scroll', listenScrollEvent)
  })

  return (
        <main className={cx(classes.content, { [classes.disableScroll]: show })}
          style={{ backgroundColor: mainColor }}
        >
          {children}
        </main>

Below is the relevant CSS class for reference:

  content: {
    backgroundColor: theme.colors.gray[0],
    position: 'fixed',
    top: params.headerHeight,
    right: 0,
    left: 0,
    bottom: 0,
    overflowY: 'auto',
    [mq(theme.breakpoints.sm)]: {
      right: 0,
      left: params.sidebarCollapsedWidth
    }

I am unable to determine why window.scrollY does not seem to be functioning properly as intended. I even tried logging window.scrollY in the console but received no output. Any guidance from an expert would be greatly appreciated. Thank you.

Looking forward to your help!

Answer №1

Upon reviewing your code, it appears that there may be a potential issue with the useEffect. However, without observing your code in action, it is challenging to pinpoint the exact problem. I quickly created a test scenario based on your example, which seems to achieve the intended functionality:

import { useState, useEffect } from 'react';
import reactLogo from './assets/react.svg';
import viteLogo from '/vite.svg';
import './App.css';

const INITIAL_COLOR = "purple"

function App() {
  const [color, setColor] = useState(INITIAL_COLOR);

  const listenScrollEvent = () => {
    setColor(window.scrollY < 10 ? INITIAL_COLOR : "gray");
  };

  useEffect(() => {
    window.addEventListener('scroll', listenScrollEvent);
  }, []);

  return (
    <>
      <div style={{ backgroundColor: color }}>
        <a href="https://vitejs.dev" target="_blank" style={{ paddingBottom: "1000px" }}>
          <img src={viteLogo} className="logo" alt="Vite logo" />
        </a>
        <a href="https://react.dev" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
    </>
  );
}

export default App;

You can view a demonstration of the code here:

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

Is there a way to design OpenStreetMap similar to the aesthetic of coronavirus.app?

Exploring the realm of OpenStreetMap, leaflet, and map tiles has piqued my interest! My initial goal is to create a visually appealing map for data visualization. Having past experience with styling maps client-side through Google Maps, I encountered a r ...

Dynamic image swapping using JSON key in Angular

Trying to display different icons based on a property that contains specific words. If the property includes "Health Care" or "Health Care .....", I want to show one image, otherwise another. I've tried using ng-show but my syntax seems off. Any sugge ...

Manage the border around the image by incorporating a timer countdown - starting from a complete circle, transitioning to a partial arc, and finally disappearing completely

My expertise lies in html, css, and angularjs for front-end development. I have an image that is initially surrounded by a thick border forming a full circle. As a countdown of one minute begins, I want the border to gradually disappear as time progresses. ...

Discover the best practices for implementing light secondary colors in material-ui framework

I have a question about utilizing different colors from my theme palette: palette: { primary: { main: '#d05ce3', }, secondary: { light: '#0066ff', main: '#0044ff', }, While I know how to use the secondary color like ...

The issue arises when React child props fail to update after a change in the parent state

Here's the main issue I'm encountering: I am opening a websocket and need to read a sessionId from the first incoming message in order to use it for subsequent messages. This should only happen once. I have a child component called "processMess ...

Get the docx file as a blob

When sending a docx file from the backend using Express, the code looks like this: module.exports = (req, res) => { res.status(200).sendFile(__dirname+"/output.docx") } To download and save the file as a blob in Angular, the following code snippet i ...

Transforming a React Class Component into a Functional Component

Attempting to refactor the following code from a React Class Component to a Function Component has presented some challenges. The error message received was "Expected an assignment or function call and instead saw an expression. eslint no-unused-expression ...

Tips for evaluating style modifications on mouseover using cypress

Trying to test hover styles on table rows but encountering issues: Here is the code snippet I am testing: it("Table rows should display correct hover styles", () => { cy.get("table>tbody>tr").each(($el, index, $list) =&g ...

Keeping class secrets hidden?

This thought just crossed my mind, and I'm looking for a way to make classes private in TypeScript. Let me explain the situation: Inside my directory Typescript/circle/circle.ts, I have the following code snippet: class Circle { PI:number = 3.14; ...

Overruled fashion

Here is the HTML code from my custom page: <div class="notes quotes-notification member-savings f-left"> <h2>My Notifications</h2> <ul> <li><b>I need to make some changes in the HTML, different from other pages you have ...

Responsive Design in React-restructuring the interface

I'm currently in the process of developing a React application and I am contemplating whether to incorporate bootstrap for creating a responsive design. I'm debating between utilizing the core bootstrap library or opting for react-bootstrap. In ...

Tips for defining a relative path in the base URL with AngularJS

Encountering an issue with AngularJS routes related to file paths. The folder structure is as follows: js -> Angular -> css -> Bootstrap -> index.html Routes work fine when hosted on a server like IIS. However, copying and pasting the direct ...

Encountering issues with accessing a variable before its initialization in the getServerSideProps function in

Currently, I am working on setting up Firebase and configuring the APIs and functions to retrieve necessary data in my firebase.tsx file. Afterwards, I import them into my pages/index.tsx file but I am encountering an issue where I cannot access exports af ...

How do you properly perform typechecking on a custom fetch function in ReactQuery? I'm encountering an error that states: "....is of an unknown type."

Currently, I am working with typescript + react-query and creating a custom fetch function. I am struggling to properly type this function and encountering a TypeScript error when attempting to use myQuery.error.message const locationQuery: QueryObserverRe ...

When attempting to call a function from a separate JavaScript file in Vue, the returned value is showing

My goal is to trigger my notification function from another JS file, but I keep getting an undefined error. The code snippet for the notification function in notification.js is as follows: function notification(message, level = 'success') { ...

Oops! An issue occurred during the `ng build` command, indicating a ReferenceError with the message "Buffer is not defined

I'm facing an issue while trying to utilize Buffer in my angular component ts for encoding the Authorization string. Even after attempting npm i @types/node and adding "node" to types field in tsconfig.json, it still doesn't compile with ng buil ...

Failure to validate two dates, even when they are both in date format within AngularJS

Although it may seem silly to ask, I am confused as to why this is not working. Even though all the values appear fine in debug mode. My goal is to display an error if the productionStartFrom date is before the current date. Controller scope.currentDate ...

What is the abbreviated term for personalized elements in React Native development?

After discovering that custom components can be created like this: const CustomComp=()=>{ console.log('Created custom comp'); return(<View></View>); } export default function App(){ return(<View style={{flex:1}}> &l ...

A guide on implementing radio buttons in Angular 2 and sending the selected value via a HTTP post request

As a newcomer to Angular 2, I am struggling with the following code: Here is my HTML <form action="POST" (submit)="register()" class="aa-login-form"> <input type="radio" [(ngModel)]="gender" name="sex" value="MALE"> Male <input ...

What is the best way to vertically align my content in the center?

Is there a way to vertically center all of the text content, especially focusing on the drop-down button and block, here? Despite my efforts to research and find solutions online, I have not been able to achieve the desired visual results. I am restricted ...