How to manipulate browser url in Inertia.js?

I've been using an IntersectionObserver to update the url of my SPA while the user scrolls down the page like so:

const sections = document.querySelectorAll('section')
const options = {
    threshold: 0.5
}
const observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            router.push('#' + entry.target.id)
        }
    })
}, options)
sections.forEach(section => {
    observer.observe(section)
})

but how do I do this in Inertia.js since it doesn't have the router.push method? I'm using Inertia with a Vue 3 frontend.

Upvotes: 3

Views: 7339

Answers (2)

PHANTOM-X
PHANTOM-X

Reputation: 586

you can use this method, in my case I have multi tabs page.

import { router } from '@inertiajs/react'


    const handleTabChange = (e) => {
        setInrtiaUrl(
            router.visit(
                route('dashboard', [user.id, { tab: e }]) // { tab: '1' } is the query parameter
            )
        )
        setIndex(e)
    }


then set handleTabChange on your onChange={(event, value) => handleTabChange(value)} method

url: http://127.0.0.1:8000/dashboard?tab=1

enter image description here

Upvotes: 0

Jedupont
Jedupont

Reputation: 437

Hashes seem to be preserved by Inertia when navigating from frontend: https://github.com/inertiajs/inertia/pull/257

However, this does not seem to be the case from the server: https://github.com/inertiajs/inertia/issues/729#issuecomment-1017619220

If this is not a problem for you, can you try simply visiting the same URL and adding the hash?

const id = entry.target.id
const urlWithFragment = `${url}#${id}`

Inertia.visit(urlWithFragment)

By default, the http method is get, but you can customize it:

Inertia.visit(urlWithFragment, {method: 'post'})

If you use ziggy you can easily recover the current route:

const currentRoute = route().current()
const url = route(currentRoute)

const urlWithFragment = `${url}#${id}`

Upvotes: 2

Related Questions