Search code examples
reactjsrenderinguse-effecttailwind-css

Change the style of navbar on route change


I am using this code to change the style of the navbar when it routes to different pages.

But if I use the below code page becomes unresponsive because of re-rendering. If I pass an empty [] or pass location as the second element in useEffect, then it doesn't work.

So what is the alternative for this?

const [active, setActive] = React.useState(false);
const location = useLocation();

React.useEffect(() => {
  if (location.pathname === "/Catalogues" || location.pathname === "/About") {
    setActive(true);
  }
});
return (
  <>
    <nav className={active ? "bg-white" : "bg-black"}>
      <div>.....</div>
    </nav>
  </>
);

Solution

  • You need setActive, but more importantly location as a dependency of the useEffect

     React.useEffect(() => {
                if ((location.pathname === "/Catalogues") || (location.pathname === "/About")) {
                    setActive(true);
                }
            }, [location, setActive]);
    

    Edit: it seems very unnecessary to have active in local state you can simply set a const like so

     const isActive = (location.pathname === "/Catalogues") || (location.pathname === "/About");
    

    Then delete the useEffect and useState