useLocation
useLocation is a plugin for handling location data and navigation.
# Snippet
# navigate / <Navigate .../>
navigate(href, options?) changes the current location programmatically. <Navigate/> is a JSX wrapper around the same function, for when you want to redirect declaratively from inside a route.
# Arguments
| name | type | description |
|---|---|---|
| href | url | When the href is not absolute (i.e. starting with /, # or http) it will navigate relative to window.location.href. |
| params? | key-value pairs object | used to replace params in the href for the URI encoded equivalents. <Navigate href="/some/:cat/:page" params={{ cat: 'variété', page: 'touché' }}/>will navigate to /some/vari%C3%A9t%C3%A9/touch%C3%A9. Same with the function version, navigate("/some/:cat/:page", { params: { cat: 'variété', page: 'touché' } }) |
| replace? | boolean [false] | to replace the browser history entry |
| scroll? | boolean [true] | to scroll to the top of the page |
# <Navigate/> Tag
Example using params
# Navigate Function
Example using params
# location
Returns location data in a reactive object
# Properties
| name | type | description |
|---|---|---|
| protocol | string | window.location.protocol |
| origin | string | window.location.origin |
| href | signal | window.location.href |
| pathname | signal | window.location.pathname |
| path | signal | window.location.pathname + window.location.hash |
| hash | signal | window.location.hash |
| search | signal | window.location.search |
| searchParams | Record<string, string> | A key-value pairs object with URI decoded values of searchParams, such as: {search:'variété'} |
| params | Record<string, string> | A key-value pairs object with URI decoded values of Route params, such as: {page:'variété'} |
# Log of `location`
We modify the location to trigger reactivity based on the location
# useBeforeLeave
Register a callback to run whenever the user tries to leave the current route. The callback can be sync or async; if it returns (or resolves to) false, navigation is cancelled. Rejecting a returned promise counts as false. Call useBeforeLeave from within a route's rendering — the guard is automatically cleared once the user navigates to a location outside the route's path.
# Arguments
| name | type | description |
|---|---|---|
| fn | () => boolean | Promise<boolean> | returning (or resolving to) false cancels the navigation. A rejected promise is treated as false. |
# Preventing navigation
Example preventing navigation