skip to Main Content

I want to change the color of my navbar from transparent to ‘bg-red-50’ when I start scrolling. Following is my approach to this issue. The background is transparent and isn’t changing on scroll. Moreover, nothing is being logged to console suggesting that handleScroll function isn’t being called at all.

"use client";
import { useEffect, useState } from "react";

const NavLayout = ({ layout, children }) => {
    const [scrolling, setScrolling] = useState(false);

    useEffect(() => {
        const handleScroll = () => {
            if (window.scrollY > 0) {
                setScrolling(true);
            } else {
                setScrolling(false);
            }
        };
        window.addEventListener("scroll", handleScroll);
        return () => {
            window.removeEventListener("scroll", handleScroll);
        };
    }, []); 

    return (
        <nav
            className={`${layout} absolute top-3 left-3 w-[98%] rounded py-2 px-10 text-xl ${
                scrolling ? "bg-red-50" : ""
            } z-50 h-[70px]`}
        >
            {children}
        </nav>
    );
};

export default NavLayout;

Can anyone point out what I am doing wrong?

2

Answers


  1. First make sure you have imported and used the ‘NavLayout’ component correctly in your application,then make sure that you are using a browser that supports the scroll event and if there are any other event listeners on the window object that might conflict with your scroll event listener.

    Login or Signup to reply.
  2. You can use useRef instead of using state to manage scrolled or not. Because you don’t want to re-render multiple times when scrolling, its basically affect the performance.

    const NavLayout = ({ layout, children }) => {
        const [scrolling, setScrolling] = useState(false);
        const nav = useRef(null); // use ref
        useEffect(() => {
            const handleScroll = () => {
                if (window.scrollY > 0) { // scroll down
                    !nav.current.classList.contains("bg-red-50") && nav.current.classList.add("bg-red-50");
                } else if(window.scrollY === 0) { // when come back to top 
                    nav.current.classList.remove("bg-red-50");
                }
            };
            window.addEventListener("scroll", handleScroll);
            return () => {
                window.removeEventListener("scroll", handleScroll);
            };
        }, []); 
    
        return (
            <nav ref = {nav}
                className={`${layout} absolute top-3 left-3 w-[98%] rounded py-2 px-10 text-xl z-50 h-[70px]`}
            >
                {children}
            </nav>
        );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search