Search code examples
javascripthtmlcssreactjs

Override React Component with CSS Style


so now I have a NavBar component.

I have this javascript code that lets the navbar have background color when it reaches 50px. How can I apply this javascript to only one file and not all.

I mean I want this scroll effect to only apply in homepage not in aboutPage or any other.

  const [sticky, setSticky] = useState(false);
  useEffect(() => {
    window.addEventListener("scroll", () => {
      window.scrollY > 50 ? setSticky(true) : setSticky(false);
    });
  }, []);


  return (
    <nav className={`container ${sticky ? "dark-nav" : ""}`}>
      <Link to="/">
        <img src={Logo} className="Logo" alt="" />
      </Link>
      <ul className={mobileMenu ? "" : "hide-mobile-menu"}>
        <li>
          <NavLink to="/">Home</NavLink>
        </li>
        <li>
          <NavLink to="/About">About</NavLink>
        </li>
        <li>
          <NavLink to="/Services">Services</NavLink>
        </li>
        <li>
          <NavLink to="/Contact">
            <btn className="btn">Contact Us</btn>
          </NavLink>
        </li>
      </ul>
      <img src={menuIcon} alt="" className="menu-icon" onClick={toggleMenu} />
    </nav>
  );

Solution

  • You can add a check to test the current page URL before applying the scroll event listener. Use window.location.pathname to get the path without the domain.

    useEffect(() => {
        const path = window.location.pathname.trim();
        if (path === "" || path === "/") { // allow for trailing slash
            window.addEventListener("scroll", () => {
                 window.scrollY > 50 ? setSticky(true) : setSticky(false);
            });
        }
    }, []);