sv-router
Functions
createRouter(routes)
Sets up a new router instance with the given routes configuration.
Parameters:
routes
- An object mapping paths to components or nested routes
Returns: A router API object with the following properties:
p
- Path constructornavigate
- Navigation functionisActive
- Route activation checkerroute
- Current route information
p(path, params?)
Constructs a path with type-safe parameter substitution.
Parameters:
path
- The route pathparams
- (Optional) Parameters to substitute in the path
Returns: A string representing the constructed path
navigate(path, options?)
Programmatically navigate to a route.
Parameters:
path | number
- Either:- A string path to navigate to, or
- A number representing steps to navigate in history (negative for back, positive for forward)
options
- (Optional) Navigation optionsreplace
- Replace current history entry instead of pushingsearch
- Query stringstate
- History state to savehash
- URL hash fragmentscrollToTop
- Scroll behavior ("auto" | "instant" | "smooth" | false
)params
- Parameters to substitute in the path
isActive(path, params?)
Checks if a given path is currently active.
Parameters:
path
- The route to checkparams
- (Optional) Parameters to substitute in the path
Returns: Boolean indicating if the route is active
Methods:
startsWith(path: string, params?: Record<string, string | number>): boolean
- Returns true if the current route starts with the given path and parameters.
route
An object containing information about the current route.
Properties:
params
- Parameters from the current routepathname
- Current pathsearch
- Query string portion of the URLstate
- History statehash
- Hash fragment of the URL
isActiveLink
A Svelte action that adds a class to anchors when their href
matches the current route.
Parameters:
options
- (Optional) Configuration objectclassName
- The class to add when active (defaults tois-active
)startsWith
- Whether to match the start of the path (defaults tofalse
)
Components
<Router />
The component that renders the current route.
This component will automatically render the component that matches the current URL path. It uses the routes configuration provided to createRouter()
to determine which component to render.
Variables
searchParams
A reactive URL search parameters object that updates the URL when changed.
Properties and Methods:
- All standard
URLSearchParams
methods (get
,set
,has
,delete
, etc.)options
- (Optional) Forappend
,delete
,set
andsort
replace
- Wheter to create a new entry in the history stack (defaults tofalse
)
Types
Hooks
Configuration object for route lifecycle hooks.
Properties:
beforeLoad?(): void | Promise<void>
- A function called before the route is loaded. You can throw anavigate
call to redirect.afterLoad?(): void
- A function called after the route is loaded.