Search code examples
reactjsreact-hooksreact-router-domconditional-rendering

I cant make a navigation bar to change its background only on main(/) content in REACT


I have a Header component like this

 const [small, setSmall] = useState(false)
    
    console.log(window.location.pathname)
    console.log(window.location.pathname === '/')

     useEffect(() => {
      
       if (typeof window !== "undefined") {
        if(window.location.pathname === '/'){
          window.addEventListener("scroll", () =>
          setSmall(window.scrollY > 640),
        
          );
        }
           
       }
     }, []);

html:

 <nav className={`padding-280px ${ small  ? "colorful" : "transparent"}`}

the problem is that when am on different Route, console says false, but Header component changes anyway. any tips?


Solution

  • Issues

    The useEffect hook runs only once when the component mounts. This means the window.location.pathname value from when the component mounted is closed over in callback scope. The logic doesn't invalidate the small state when not on the home "/" page.

    Solution

    I suggest using the useMatch hook to test if on the home "/" pathname and conditionally apply either the "colorful" or "transparent" class when the current location is "/" and the scroll position is greater than 640px. Don't forget to return a cleanup function to remove the scroll event listener when the component unmounts.

    Example:

    const homeMatch = useMatch("/");
    
    const [small, setSmall] = useState(false);
    
    useEffect(() => {
      const scrollHandler = () => {
        setSmall(window.scrollY < 640);
      };
    
      if (typeof window !== "undefined") {
        window.addEventListener("scroll", scrollHandler, { passive: true });
      }
    
      return () => {
        window.removeEventListener("scroll", scrollHandler, { passive: true });
      };
    }, []);
    
    ...
    
    <nav
      className={[
        "padding-280px",
        homeMatch && small ? "transparent": "colorful"
      ].join(" ")}
    >
      ...
    </nav>
    

    Edit i-cant-make-a-navigation-bar-to-change-its-background-only-on-main-content-in