useNavigate
useNavigate
provides a function for navigating routes
ts
import { useNavigate } from "solid-start";// ---cut---const navigate = useNavigate();
ts
import { useNavigate } from "solid-start";// ---cut---const navigate = useNavigate();
Usage
Navigating to a new route
You can use useNavigate
inside the main component body to get a navigate
function you can use in any of your event handlers or reactive updates.
js
import { useNavigate } from "solid-start";function Component() {const navigate = useNavigate();const handleClick = () => {// do some stuff then...navigate("/home");}return <button onClick={handleClick}>Do Something</button>}
js
import { useNavigate } from "solid-start";function Component() {const navigate = useNavigate();const handleClick = () => {// do some stuff then...navigate("/home");}return <button onClick={handleClick}>Do Something</button>}
Replacing the current route
Sometimes you want to replace the current place in the navigation history. You can do that by setting the replace
option to true
.
js
const navigate = useNavigate();if (unauthorized) {navigate("/login", { replace: true });}
js
const navigate = useNavigate();if (unauthorized) {navigate("/login", { replace: true });}
Reference
useNavigate()
Call useNavigate()
inside a component to get a function you can use to navigate.
tsx
import {} from "solid-start"; useNavigate function() { Component const= navigate (); useNavigate }
tsx
import {} from "solid-start"; useNavigate function() { Component const= navigate (); useNavigate }
Returns
A function to do route navigation. The method accepts a path to navigate to and an optional object with the following options:
- resolve (boolean, default
true
): resolve the path against the current route - replace (boolean, default
false
): replace the history entry - scroll (boolean, default
true
): scroll to top after navigation - state (any, default
undefined
): pass custom state tolocation.state
Note: The state is serialized using the structured clone algorithm which does not support all object types.