T
TanStack•2mo ago
fair-rose

URL hash manipulation ??

Hey everyone, This might seem like a stupid question, but how do you manipulate a url hash in tanstack router ? Like how could I read, update and delete hello from this url http://example.com/page#hello ? Thanks in advance for any help 😀
2 Replies
foreign-sapphire
foreign-sapphire•2mo ago
I believe you can update with useNavigate.
import { useNavigate } from '@tanstack/react-router'

// Component
const navigate = useNavigate()

// In useEffect
useEffect(() => {
// Update hash there
navigate({ to: '/posts', hash: 'my-hash' })
}, [navigate])

// or in JSX, e.g. onClick
<button
onClick={() =>
navigate({
to: '/posts',
hash: 'my-hash',
})
}
>
import { useNavigate } from '@tanstack/react-router'

// Component
const navigate = useNavigate()

// In useEffect
useEffect(() => {
// Update hash there
navigate({ to: '/posts', hash: 'my-hash' })
}, [navigate])

// or in JSX, e.g. onClick
<button
onClick={() =>
navigate({
to: '/posts',
hash: 'my-hash',
})
}
>
Or simply using <Link>
<Link
to="/blog/post/$postId"
params={{
postId: 'my-first-blog-post',
}}
// Hash
hash="section-1"
>
Section 1
</Link>
<Link
to="/blog/post/$postId"
params={{
postId: 'my-first-blog-post',
}}
// Hash
hash="section-1"
>
Section 1
</Link>
I think if you provide empty hash then it deletes it. And you can read the hash using useRouterState(). router.location.hash
fair-rose
fair-roseOP•2mo ago
what a perfect answer thank you @konhi 🫶

Did you find this page helpful?