Search code examples
javascriptcssreactjstypescriptscroll

change background color when scrolling (scrolly not working)


i have a component that i want to change the background color when the user scrolls through the page

Here is my what i have tried

  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>
  )

and this is the css class for your 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
    }

can you someone please help me figure out why the window.scrollY is not working i have tried to console.log(window.scrollY) and see if get anything on the console but im getting nothing on their as well cant figure out what im doing wrong here .would like the help from an expert

Thanks in advance


Solution

  • My initial thought when I reviewed your code is that you might have a faulty useEffect. That being said, without seeing your code in action, it's hard to tell what exactly is wrong. I create a quick spike which mostly mirrors your example above and it does what you were intending:

    import { useState, useEffect } from 'react';
    import reactLogo from './assets/react.svg';
    import viteLogo from '/vite.svg';
    import './App.css';
    
    const INIT_COLOR = "purple"
    
    function App() {
      const [color, setColor] = useState(INIT_COLOR);
    
      const listenScrollEvent = () => {
        setColor(window.scrollY < 10 ? INIT_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;
    

    Here's a demo of the code above in action: https://www.loom.com/share/46435ccb648f44d498eee453f7820ec8?sid=c3bd2595-270e-47b5-a452-ac4efdc431c8