Next.js Discord

Discord Forum

"useLocation" - Router Problem

Unanswered
Oak apple gall wasp posted this in #help-forum
Open in Discord
Oak apple gall waspOP
Error: useLocation() may be used only in the context of a <Router> component.


const Navbar = ( props:Props) => {
    const [open, setOpen] = useState(false);
    const navRef = useRef<HTMLDivElement>(null);
    const location = useLocation();
    console.log("ads")
    useEffect(() => {
      console.log("adabs")
      const listen = () => {
        const nav = navRef.current;
        console.log("adfasdsas", !!nav, document.body.scrollTop)
        if (!nav) return;
        if (document.documentElement.scrollTop > 40) {
          nav.classList.add("black");
        } else {
          nav.classList.remove("black");
        }
      }
      window.addEventListener("scroll", listen)
      listen();
      return () => {
        window.removeEventListener("scroll", listen)
      }
    }, [location]);

5 Replies

European sprat
useLocation is for react-router and react-router shouldn't be used with nextjs
@European sprat useLocation is for react-router and react-router shouldn't be used with nextjs
Oak apple gall waspOP
Yeah i got that but is there a way to do this using nextjs
Or an alternative solution
European sprat
i don't know what useLocation does
if it's a wrapper for location you can just use window.location in client components