Next.js Discord

Discord Forum

How to get hash from URL without window.location.hash?

Unanswered
Super_Kenil posted this in #help-forum
Open in Discord
I am trying to set "active" class on the #hash link in my Top Navigation Bar. I want to highlight whichever link's hash is present in the URL, whatever solution I looked for had window.location.hash or router.asPath from "next/router" and the splitting that URL with #. But as I am using App Dir, I am unable to get any nextjs related solutions.

Help me get what I want, let me know if you don't understand my question as English is not my first language. Thanks

6 Replies

Asiatic Lion
import { useParams } from "next/navigation";


did you try this ?
or this import { usePathname } from "next/navigation";
usePathname only gives pathname, not the hash after the pathname

And as for the useParams, it doesn't give me hash either, and neither of it's methods gives me hash, I am only able to read the query params with it, not the hash
you have no downsides with window.location.hash as it is forced client anyway (has isn't sent to server, so it can't prerender like usePathname)
I know about that,
but I just think, just as react-router-dom provides everything you need, there should be something Nextjs specific things as well

Eg. I am only able to read the query params with useParams hook, and not write query params.
I know I can write it with next/link, but that would happen only when the user clicks on the Link, not programmatically. And if I wanna do it programmatically, then I would have to use router.push, and write down query params myself to the router.push method
It's just a question, as I thought that there could be something. But it turns out there's nothing I can use except for the window.location.hash right now. So thanks for helping me out.