Solid Router

A universal router for Solid inspired by Ember and React Router

README

Solid Router


Solid Router npm Version


A router lets you change your view based on the URL in the browser. This allows your "single-page" application to simulate a traditional multipage site. To use Solid Router, you specify components called Routes that depend on the value of the URL (the "path"), and the router handles the mechanism of swapping them in and out.

Solid Router is a universal router for SolidJS - it works whether you're rendering on the client or on the server. It was inspired by and combines paradigms of React Router and the Ember Router. Routes can be defined directly in your app's template using JSX, but you can also pass your route configuration directly as an object. It also supports nested routing, so navigation can change a part of a component, rather than completely replacing it.

It supports all of Solid's SSR methods and has Solid's transitions baked in, so use it freely with suspense, resources, and lazy components. Solid Router also allows you to define a data function that loads parallel to the routes (render-as-you-fetch).

  - useParams
  - useMatch
  - useRoutes

Getting Started


Set Up the Router


  1. ```sh
  2. > npm i @solidjs/router
  3. ```

Install @solidjs/router, then wrap your root component with the Router component:

  1. ``` js
  2. import { render } from "solid-js/web";
  3. import { Router } from "@solidjs/router";
  4. import App from "./App";

  5. render(
  6.   () => (
  7.     <Router>
  8.       <App />
  9.     </Router>
  10.   ),
  11.   document.getElementById("app")
  12. );
  13. ```

This sets up a context so that we can display the routes anywhere in the app.

Configure Your Routes


Solid Router allows you to configure your routes using JSX:

1. Use the Routes component to specify where the routes should appear in your app.


  1. ``` js
  2. import { Routes, Route } from "@solidjs/router"

  3. export default function App() {
  4.   return <>
  5.     <h1>My Site with Lots of Pages</h1>
  6.     <Routes>
  7. </Routes>
  8.   </>
  9. }
  10. ```

2. Add each route using the Route component, specifying a path and an element or component to render when the user navigates to that path.

  1. ``` js
  2. import { Routes, Route } from "@solidjs/router"

  3. import Home from "./pages/Home"
  4. import Users from "./pages/Users"

  5. export default function App() {
  6.   return <>
  7.     <h1>My Site with Lots of Pages</h1>
  8.     <Routes>
  9.       <Route path="/users" component={Users} />
  10.       <Route path="/" component={Home} />
  11.       <Route path="/about" element={<div>This site was made with Solid</div>} />
  12.     </Routes>
  13.   </>
  14. }
  15. ```

3. Lazy-load route components

This way, the Users and Home components will only be loaded if you're navigating to /users or /, respectively.

  1. ``` js
  2. import { lazy } from "solid-js";
  3. import { Routes, Route } from "@solidjs/router"
  4. const Users = lazy(() => import("./pages/Users"));
  5. const Home = lazy(() => import("./pages/Home"));

  6. export default function App() {
  7.   return <>
  8.     <h1>My Site with Lots of Pages</h1>
  9.     <Routes>
  10.       <Route path="/users" component={Users} />
  11.       <Route path="/" component={Home} />
  12.       <Route path="/about" element={<div>This site was made with Solid</div>} />
  13.     </Routes>
  14.   </>
  15. }
  16. ```

Create Links to Your Routes


Use the A component to create an anchor tag that takes you to a route:

  1. ``` js
  2. import { lazy } from "solid-js";
  3. import { Routes, Route, A } from "@solidjs/router"
  4. const Users = lazy(() => import("./pages/Users"));
  5. const Home = lazy(() => import("./pages/Home"));

  6. export default function App() {
  7.   return <>
  8.     <h1>My Site with Lots of Pages</h1>
  9.     <nav>
  10.       <A href="/about">About</A>
  11.       <A href="/">Home</A>
  12.     </nav>
  13.     <Routes>
  14.       <Route path="/users" component={Users} />
  15.       <Route path="/" component={Home} />
  16.       <Route path="/about" element={<div>This site was made with Solid</div>} />
  17.     </Routes>
  18.   </>
  19. }
  20. ```

The `` tag also has an `active` class if its href matches the current location, and `inactive` otherwise. **Note:** By default matching includes locations that are descendents (eg. href `/users` matches locations `/users` and `/users/123`), use the boolean `end` prop to prevent matching these. This is particularly useful for links to the root route `/` which would match everything.


proptypedescription
|----------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
hrefstringThe
noScrollbooleanIf
replacebooleanIf
stateunknown[Push
inactiveClassstringThe
activeClassstringThe
endbooleanIf

The Navigate Component

Solid Router provides a Navigate component that works similarly to A, but it will _immediately_ navigate to the provided path as soon as the component is rendered. It also uses the href prop, but you have the additional option of passing a function to href that returns a path to navigate to:

  1. ``` js
  2. function getPath ({navigate, location}) {
  3.   //navigate is the result of calling useNavigate(); location is the result of calling useLocation().
  4.   //You can use those to dynamically determine a path to navigate to
  5.   return "/some-path";
  6. }

  7. //Navigating to /redirect will redirect you to the result of getPath
  8. <Route path="/redirect" element={<Navigate href={getPath}/>}/>
  9. ```

Dynamic Routes


If you don't know the path ahead of time, you might want to treat part of the path as a flexible parameter that is passed on to the component.

  1. ``` js
  2. import { lazy } from "solid-js";
  3. import { Routes, Route } from "@solidjs/router"
  4. const Users = lazy(() => import("./pages/Users"));
  5. const User = lazy(() => import("./pages/User"));
  6. const Home = lazy(() => import("./pages/Home"));

  7. export default function App() {
  8.   return <>
  9.     <h1>My Site with Lots of Pages</h1>
  10.     <Routes>
  11.       <Route path="/users" component={Users} />
  12.       <Route path="/users/:id" component={User} />
  13.       <Route path="/" component={Home} />
  14.       <Route path="/about" element={<div>This site was made with Solid</div>} />
  15.     </Routes>
  16.   </>
  17. }
  18. ```

The colon indicates that id can be any string, and as long as the URL fits that pattern, the User component will show.

You can then access that id from within a route component with useParams:


  1. ``` js
  2. //async fetching function
  3. import { fetchUser } ...

  4. export default function User () {

  5.   const params = useParams();

  6.   const [userData] = createResource(() => params.id, fetchUser);

  7.   return <A href={userData.twitter}>{userData.name}</A>
  8. }
  9. ```

Optional Parameters


Parameters can be specified as optional by adding a question mark to the end of the parameter name:

  1. ``` js
  2. //Matches stories and stories/123 but not stories/123/comments
  3. <Route path='/stories/:id?' element={<Stories/>} />
  4. ```

Wildcard Routes


:param lets you match an arbitrary name at that point in the path. You can use * to match any end of the path:

  1. ``` js
  2. //Matches any path that begins with foo, including foo/, foo/a/, foo/a/b/c
  3. <Route path='foo/*' component={Foo}/>
  4. ```

If you want to expose the wild part of the path to the component as a parameter, you can name it:

  1. ``` js
  2. <Route path='foo/*any' element={<div>{useParams().any}</div>}/>
  3. ```

Note that the wildcard token must be the last part of the path; foo/*any/bar won't create any routes.

Multiple Paths


Routes also support defining multiple paths using an array. This allows a route to remain mounted and not rerender when switching between two or more locations that it matches:

  1. ``` js
  2. //Navigating from login to register does not cause the Login component to re-render
  3. <Route path={["login", "register"]} component={Login}/>
  4. ```


Data Functions

In the above example, the User component is lazy-loaded and then the data is fetched. With route data functions, we can instead start fetching the data parallel to loading the route, so we can use the data as soon as possible.

To do this, create a function that fetches and returns the data using createResource. Then pass that function to the data prop of the Route component.


  1. ``` js
  2. import { lazy } from "solid-js";
  3. import { Route } from "@solidjs/router";
  4. import { fetchUser } ...

  5. const User = lazy(() => import("./pages/users/[id].js"));

  6. //Data function
  7. function UserData({params, location, navigate, data}) {
  8.   const [user] = createResource(() => params.id, fetchUser);
  9.   return user;
  10. }

  11. //Pass it in the route definition
  12. <Route path="/users/:id" component={User} data={UserData} />;
  13. ```

When the route is loaded, the data function is called, and the result can be accessed by calling useRouteData() in the route component.

  1. ``` js
  2. //pages/users/[id].js
  3. import { useRouteData } from '@solidjs/router';
  4. export default function User() {
  5.   const user = useRouteData();
  6.   return <h1>{user().name}</h1>;
  7. }
  8. ```

As its only argument, the data function is passed an object that you can use to access route information:

keytypedescription
|-----------|------------------------------------------------|-------------------------------------------------------------------------------------------------------------|
paramsobjectThe
location`{An
navigate`(to:A
dataunknownThe

A common pattern is to export the data function that corresponds to a route in a dedicated route.data.js file. This way, the data function can be imported without loading anything else.

  1. ``` js
  2. import { lazy } from "solid-js";
  3. import { Route } from "@solidjs/router";
  4. import { fetchUser } ...
  5. import UserData from "./pages/users/[id].data.js";
  6. const User = lazy(() => import("/pages/users/[id].js"));

  7. // In the Route definition
  8. <Route path="/users/:id" component={User} data={UserData} />;
  9. ```

Nested Routes

The following two route definitions have the same result:

  1. ``` js
  2. <Route path="/users/:id" component={User} />
  3. ```
  1. ``` js
  2. <Route path="/users">
  3.   <Route path="/:id" component={User} />
  4. </Route>
  5. ```
`/users/:id` renders the `` component, and `/users/` is an empty route.

Only leaf Route nodes (innermost Route components) are given a route. If you want to make the parent its own route, you have to specify it separately:

  1. ``` js
  2. //This won't work the way you'd expect
  3. <Route path="/users" component={Users}>
  4.   <Route path="/:id" component={User} />
  5. </Route>

  6. //This works
  7. <Route path="/users" component={Users} />
  8. <Route path="/users/:id" component={User} />

  9. //This also works
  10. <Route path="/users">
  11.   <Route path="/" component={Users} />
  12.   <Route path="/:id" component={User} />
  13. </Route>
  14. ```

You can also take advantage of nesting by adding a parent element with an ``.
  1. ``` js

  2. import { Outlet } from "@solidjs/router";

  3. function PageWrapper () {
  4.   return <div>
  5.     <h1> We love our users! </h1>
  6.     <Outlet/>
  7.     <A href="/">Back Home</A>
  8.   </div>
  9. }

  10. <Route path="/users" component={PageWrapper}>
  11.   <Route path="/" component={Users}/>
  12.   <Route path="/:id" component={User} />
  13. </Route>
  14. ```
The routes are still configured the same, but now the route elements will appear inside the parent element where the `` was declared.

You can nest indefinitely - just remember that only leaf nodes will become their own routes. In this example, the only route created is /layer1/layer2, and it appears as three nested divs.

  1. ``` js
  2. <Route path='/' element={<div>Onion starts here <Outlet />div>}>
  3.   <Route path='layer1' element={<div>Another layer <Outlet />div>}>
  4.     <Route path='layer2' element={<div>Innermost layer</div>}>Route>
  5.   </Route>
  6. </Route>
  7. ```

If you declare a data function on a parent and a child, the result of the parent's data function will be passed to the child's data function as the data property of the argument, as described in the last section. This works even if it isn't a direct child, because by default every route forwards its parent's data.

Hash Mode Router


By default, Solid Router uses `location.pathname` as route path. You can simply switch to hash mode through the `source` property on `` component.

  1. ``` js
  2. import { Router, hashIntegration } from '@solidjs/router'

  3. <Router source={hashIntegration()}><App></Router>
  4. ```

Config Based Routing


You don't have to use JSX to set up your routes; you can pass an object directly with useRoutes:

  1. ``` js
  2. import { lazy } from "solid-js";
  3. import { render } from "solid-js/web";
  4. import { Router, useRoutes, A } from "@solidjs/router";

  5. const routes = [
  6.   {
  7.     path: "/users",
  8.     component: lazy(() => import("/pages/users.js"))
  9.   },
  10.   {
  11.     path: "/users/:id",
  12.     component: lazy(() => import("/pages/users/[id].js")),
  13.     children: [
  14.       { path: "/", component: lazy(() => import("/pages/users/[id]/index.js")) },
  15.       { path: "/settings", component: lazy(() => import("/pages/users/[id]/settings.js")) },
  16.       { path: "/*all", component: lazy(() => import("/pages/users/[id]/[...all].js")) }
  17.     ]
  18.   },
  19.   {
  20.     path: "/",
  21.     component: lazy(() => import("/pages/index.js"))
  22.   },
  23.   {
  24.     path: "/*all",
  25.     component: lazy(() => import("/pages/[...all].js"))
  26.   }
  27. ];

  28. function App() {
  29.   const Routes = useRoutes(routes);
  30.   return (
  31.     <>
  32.       <h1>Awesome Site</h1>
  33.       <A class="nav" href="/">
  34.         Home
  35.       </A>
  36.       <A class="nav" href="/users">
  37.         Users
  38.       </A>
  39.       <Routes />
  40.     </>
  41.   );
  42. }

  43. render(
  44.   () => (
  45.     <Router>
  46.       <App />
  47.     </Router>
  48.   ),
  49.   document.getElementById("app")
  50. );
  51. ```

Router Primitives


Solid Router provides a number of primitives that read off the Router and Route context.

useParams


Retrieves a reactive, store-like object containing the current route path parameters as defined in the Route.

  1. ``` js
  2. const params = useParams();

  3. // fetch user based on the id path parameter
  4. const [user] = createResource(() => params.id, fetchUser);
  5. ```

useNavigate


Retrieves method to do 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 to location.state

__Note:__ The state is serialized using the structured clone algorithm which does not support all object types.

  1. ``` js
  2. const navigate = useNavigate();

  3. if (unauthorized) {
  4.   navigate("/login", { replace: true });
  5. }
  6. ```

useLocation


Retrieves reactive location object useful for getting things like pathname

  1. ``` js
  2. const location = useLocation();

  3. const pathname = createMemo(() => parsePath(location.pathname));
  4. ```

useSearchParams


Retrieves a tuple containing a reactive object to read the current location's query parameters and a method to update them. The object is a proxy so you must access properties to subscribe to reactive updates. Note values will be strings and property names will retain their casing.

The setter method accepts an object whose entries will be merged into the current query string. Values '', undefined and null will remove the key from the resulting query string. Updates will behave just like a navigation and the setter accepts the same optional second parameter as navigate and auto-scrolling is disabled by default.

  1. ``` js
  2. const [searchParams, setSearchParams] = useSearchParams();

  3. return (
  4.   <div>
  5.     <span>Page: {searchParams.page}</span>
  6.     <button onClick={() => setSearchParams({ page: searchParams.page + 1 })}>Next Page</button>
  7.   </div>
  8. );
  9. ```

useIsRouting


Retrieves signal that indicates whether the route is currently in a Transition. Useful for showing stale/pending state when the route resolution is Suspended during concurrent rendering.

  1. ``` js
  2. const isRouting = useIsRouting();

  3. return (
  4.   <div classList={{ "grey-out": isRouting() }}>
  5.     <MyAwesomeConent />
  6.   </div>
  7. );
  8. ```

useRouteData


Retrieves the return value from the data function.

In previous versions you could use numbers to access parent data. This is no longer supported. Instead the data functions themselves receive the parent data that you can expose through the specific nested routes data.


  1. ``` js
  2. const user = useRouteData();

  3. return <h1>{user().name}</h1>;
  4. ```

useMatch


useMatch takes an accessor that returns the path and creates a Memo that returns match information if the current path matches the provided path. Useful for determining if a given path matches the current route.

  1. ``` js
  2. const match = useMatch(() => props.href);

  3. return <div classList={{ active: Boolean(match()) }} />;
  4. ```

useRoutes


Used to define routes via a config object instead of JSX. See Config Based Routing.

useBeforeLeave


useBeforeLeave takes a function that will be called prior to leaving a route.  The function will be called with:

- from (_Location_): current location (before change).
- to (_string | number_}: path passed to navigate.
- options (_NavigateOptions_}: options passed to navigate.
- preventDefault (_void function_): call to block the route change.
- defaultPrevented (_readonly boolean_): true if any previously called leave handlers called preventDefault().
- retry (_void function_, _force?: boolean_ ): call to retry the same navigation, perhaps after confirming with the user. Pass true to skip running the leave handlers again (ie force navigate without confirming).

Example usage:
  1. ``` js
  2. useBeforeLeave((e: BeforeLeaveEventArgs) => {
  3.   if (form.isDirty && !e.defaultPrevented) {
  4.     // preventDefault to block immediately and prompt user async
  5.     e.preventDefault();
  6.     setTimeout(() => {
  7.       if (window.confirm("Discard unsaved changes - are you sure?")) {
  8.         // user wants to proceed anyway so retry with force=true
  9.         e.retry(true);
  10.       }
  11.     }, 100);
  12.   }
  13. });
  14. ```