useNavigate
useNavigate provides a function for navigating routes
tsimport { useNavigate } from "solid-start";// ---cut---const navigate = useNavigate();
tsimport { 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.
jsimport { useNavigate } from "solid-start";function Component() {const navigate = useNavigate();const handleClick = () => {// do some stuff then...navigate("/home");}return <button onClick={handleClick}>Do Something</button>}
jsimport { 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.
jsconst navigate = useNavigate();if (unauthorized) {navigate("/login", { replace: true });}
jsconst navigate = useNavigate();if (unauthorized) {navigate("/login", { replace: true });}
Reference
useNavigate()
Call useNavigate() inside a component to get a function you can use to navigate.
tsximport {} from "solid-start"; useNavigate function() { Component const= navigate (); useNavigate }
tsximport {} 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.