Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

location hash change doesnt trigger hashchange event #69256

Open
AmirShafikhani opened this issue Aug 24, 2024 · 2 comments
Open

location hash change doesnt trigger hashchange event #69256

AmirShafikhani opened this issue Aug 24, 2024 · 2 comments
Labels
bug Issue was opened via the bug report template. Navigation Related to Next.js linking (e.g., <Link>) and navigation.

Comments

@AmirShafikhani
Copy link

Link to the code that reproduces this issue

https://codesandbox.io/p/devbox/bitter-framework-zmcyr4?file=%2Fapp%2Fpage.tsx%3A1%2C1-37%2C21

To Reproduce

im trying to create a hash based routing in next 14 but the window hashchange event does'nt trigger when i change the location hash in these ways:

Link to #some-hash Link to #some-hash Link to #some-hash Link to #some-hash

i have even tried to push using the router like this:

router.push("#some-hash");

but non of them triggers the hashchange event.

the only way that i get succeed was using the window itself to change the hash like this:

window.location.hash = "some hash"

but i wanna use next js router to implement this. any thoughts?

Current vs. Expected behavior

i expected at least an event listener to be triggered or sth else that would help us to create hash based minimal routing systems

Provide environment information

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 11 Pro
  Available memory (MB): 16220
  Available CPU cores: 16
Binaries:
  Node: 20.15.1
  npm: N/A
  Yarn: N/A
  pnpm: N/A

Which area(s) are affected? (Select all that apply)

Navigation

Which stage(s) are affected? (Select all that apply)

next dev (local)

Additional context

No response

@AmirShafikhani AmirShafikhani added the bug Issue was opened via the bug report template. label Aug 24, 2024
@github-actions github-actions bot added the Navigation Related to Next.js linking (e.g., <Link>) and navigation. label Aug 24, 2024
@simonri
Copy link
Contributor

simonri commented Aug 24, 2024

You can use useParams() for this. Keep in mind though that the hash is only client side and will never be sent to the server.

The following code allows you to listen to hash changes:

const params = useParams();

useEffect(() => {
  console.log(window.location.hash);
}, [params]);

@AmirShafikhani
Copy link
Author

worked tnx ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Issue was opened via the bug report template. Navigation Related to Next.js linking (e.g., <Link>) and navigation.
Projects
None yet
Development

No branches or pull requests

2 participants