- Notifications
You must be signed in to change notification settings - Fork2
The official client-side router.
License
vobyjs/voby-router
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
The router forVoby.
This is a port ofSolid-App-Router to voby.
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 voby 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.
Voby router is a universal router for voby - 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.
Use it freely with suspense, resources, and lazy components. Voby router also allows you to define a data function that loads parallel to the routes (render-as-you-fetch).
- Getting Started
- Create Links to Your Routes
- Dynamic Routes
- Data Functions
- Nested Routes
- Config Based Routing
- Router Primitives
> npm i voby-routerInstallvoby-router, then wrap your root component with the Router component:
import{render}from"voby";import{Router}from"voby-router";importAppfrom"./App";render(()=>(<Router><App/></Router>),document.getElementById("app"));
This sets up a context so that we can display the routes anywhere in the app.
voby-router allows you to configure your routes using JSX:
- Use the
Routescomponent to specify where the routes should appear in your app.
import{Routes,Route}from"voby-router"exportdefaultfunctionApp(){return(<><h1>My Site with Lots of Pages</h1><Routes></Routes><> )}
- Add each route using the
Routecomponent, specifying a path and an element to render when the user navigates to that path.
import{Routes,Route}from"voby-router"importHomefrom"./pages/Home"importUsersfrom"./pages/Users"exportdefaultfunctionApp(){return(<><h1>My Site with Lots of Pages</h1><Routes><Routepath="/users"element={<Users/>}/><Routepath="/"element={<Home/>}/><Routepath="/about"element={<div>This site was made with Voby</div>}/></Routes><> )}
- Lazy-load route components
This way, theUsers andHome components will only be loaded if you're navigating to/users or/, respectively.
import{lazy}from"voby";import{Routes,Route}from"voby-router"constUsers=lazy(()=>import("./pages/Home"));constHome=lazy(()=>import("./pages/Users"));exportdefaultfunctionApp(){return(<><h1>My Site with Lots of Pages</h1><Routes><Routepath="/users"element={<Users/>}/><Routepath="/"element={<Home/>}/><Routepath="/about"element={<div>This site was made with Voby</div>}/></Routes><> )}
Use theA component to create an anchor tag that takes you to a route:
import{lazy}from"voby";import{Routes,Route,A}from"voby-router"constUsers=lazy(()=>import("./pages/Home"));constHome=lazy(()=>import("./pages/Users"));exportdefaultfunctionApp(){return(<><h1>My Site with Lots of Pages</h1><nav><Ahref="/about">About</A><Ahref="/">Home</A></nav><Routes><Routepath="/users"element={<Users/>}/><Routepath="/"element={<Home/>}/><Routepath="/about"element={<div>This site was made with Voby</div>}/></Routes><> )}
The<A> tag also has anactive class if its href matches the current location, andinactive otherwise.Note: By default matching includes locations that are descendents (eg. href/users matches locations/users and/users/123), use the booleanend prop to prevent matching these. This is particularly useful for links to the root route/ which would match everything.
| prop | type | description |
|---|---|---|
| href | string | The path of the route to navigate to. This will be resolved relative to the route that the link is in, but you can preface it with/ to refer back to the root. |
| noScroll | boolean | If true, turn off the default behavior of scrolling to the top of the new page |
| replace | boolean | If true, don't add a new entry to the browser history. (By default, the new page will be added to the browser history, so pressing the back button will take you to the previous route.) |
| state | unknown | Push this value to the history stack when navigating |
| inactiveClass | string | The class to show when the link is inactive (when the current location doesn't match the link) |
| activeClass | string | The class to show when the link is active |
| end | boolean | Iftrue, only considers the link to be active when the curent location matches thehref exactly; iffalse, check if the current locationstarts withhref |
voby-router provides aNavigate component that works similarly toA, but it willimmediately navigate to the provided path as soon as the component is rendered. It also uses thehref prop, but you have the additional option of passing a function tohref that returns a path to navigate to:
functiongetPath({navigate, location}){//navigate is the result of calling useNavigate(); location is the result of calling useLocation().//You can use those to dynamically determine a path to navigate toreturn"/some-path";}//Navigating to /redirect will redirect you to the result of getPath<Routepath="/redirect"element={<Navigatehref={getPath}/>}/>
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.
import{lazy}from"voby";import{Routes,Route}from"voby-router"constUsers=lazy(()=>import("./pages/Home"));constHome=lazy(()=>import("./pages/Users"));constHome=lazy(()=>import("./pages/User"));exportdefaultfunctionApp(){return(<><h1>My Site with Lots of Pages</h1><Routes><Routepath="/users"element={<Users/>}/><Routepath="/users/:id"element={<User/>}/><Routepath="/"element={<Home/>}/><Routepath="/about"element={<div>This site was made with Voby</div>}/></Routes><> )}
The colon indicates thatid can be any string, and as long as the URL fits that pattern, theUser component will show.
You can then access thatid from within a route component withuseParams:
//async fetching functionimport{fetchUser} ...exportdefaultfunctionUser(){constparams=useParams();const[userData]=createResource(()=>params.id,fetchUser);return<Ahref={userData.twitter}>{userData.name}</A>}
:param lets you match an arbitrary name at that point in the path. You can use* to match any end of the path:
//Matches any path that begins with foo, including foo/, foo/a/, foo/a/b/c<Routepath='foo/*'element={<Foo/>}/>
If you want to expose the wild part of the path to the component as a parameter, you can name it:
<Routepath='foo/*any'element={<div>{useParams().any}</div>}/>
Note that the wildcard token must be the last part of the path;foo/*any/bar won't create any routes.
In theabove 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 usingcreateResource. Then pass that function to thedata prop of theRoute component.
import{lazy}from"voby";import{Route}from"voby-router";import{fetchUser} ...constUser=lazy(()=>import("/pages/users/[id].js"));//Data functionfunctionUserData({params, location, navigate, data}){const[user]=createResource(()=>params.id,fetchUser);returnuser;}//Pass it in the route definition<Routepath="/users/:id"element={<User/>}data={UserData}/>;
When the route is loaded, the data function is called, and the result can be accessed by callinguseRouteData() in the route component.
//pages/users/[id].jsimport{useRouteData}from'voby-router';exportdefaultfunctionUser(){constuser=useRouteData();return<h1>{user().name}</h1>;}
As its only argument, the data function is passed an object that you can use to access route information:
| key | type | description |
|---|---|---|
| params | object | The route parameters (same value as callinguseParams() inside the route component) |
| location | { pathname, search, hash, query, state, key} | An object that you can use to get more information about the path (corresponds touseLocation()) |
| navigate | (to: string, options?: NavigateOptions) => void | A function that you can call to navigate to a different route instead (corresponds touseNavigate()) |
| data | unknown | The data returned by theparent's data function, if any. (Data will pass through any intermediate nesting.) |
A common pattern is to export the data function that corresponds to a route in a dedicatedroute.data.js file. This way, the data function can be imported without loading anything else.
import{lazy}from"voby";import{Route}from"voby-router";import{fetchUser} ...importUserDatafrom"./pages/users/[id].data.js";constUser=lazy(()=>import("/pages/users/[id].js"));// In the Route definition<Routepath="/users/:id"element={<User/>}data={UserData}/>;
The following two route definitions have the same result:
<Routepath="/users/:id"element={<User/>}/>
<Routepath="/users"><Routepath="/:id"element={<User/>}/></Route>
/users/:id renders the<User/> component, and/users/ is an empty route.
Only leaf Route nodes (innermostRoute components) are given a route. If you want to make the parent its own route, you have to specify it separately:
//This won't work the way you'd expect<Routepath="/users"element={<Users/>}><Routepath="/:id"element={<User/>}/></Route>//This works<Routepath="/users"element={<Users/>}/><Routepath="/users/:id"element={<User/>}/>//This also works<Routepath="/users"><Routepath="/"element={<Users/>}/><Routepath="/:id"element={<User/>}/></Route>
You can also take advantage of nesting by adding a parent element with an<Outlet/>.
import{Outlet}from"voby-router";functionPageWrapper(){return<div><h1> We love our users!</h1><Outlet/><Ahref="/">Back Home</A></div>}<Routepath="/users"element={<PageWrapper/>}><Routepath="/"element={<Users/>}/><Routepath="/:id"element={<User/>}/></Route>
The routes are still configured the same, but now the route elements will appear inside the parent element where the<Outlet/> 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.
<Routepath='/'element={<div>Onion starts here<Outlet/></div>}><Routepath='layer1'element={<div>Another layer<Outlet/></div>}><Routepath='layer2'element={<div>Innermost layer</div>}></Route></Route></Route>
If you declare adata 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 thedata 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.
You don't have to use JSX to set up your routes; you can pass an object directly withuseRoutes:
import{lazy,render}from"voby";import{Router,useRoutes,A}from"voby-router";constroutes=[{path:"/users",component:lazy(()=>import("/pages/users.js"))},{path:"/users/:id",component:lazy(()=>import("/pages/users/[id].js")),children:[{path:"/",component:lazy(()=>import("/pages/users/[id]/index.js"))},{path:"/settings",component:lazy(()=>import("/pages/users/[id]/settings.js"))},{path:"/*all",component:lazy(()=>import("/pages/users/[id]/[...all].js"))}]},{path:"/",component:lazy(()=>import("/pages/index.js"))},{path:"/*all",component:lazy(()=>import("/pages/[...all].js"))}];functionApp(){constRoutes=useRoutes(routes);return(<><h1>Awesome Site</h1><Aclass="nav"href="/"> Home</A><Aclass="nav"href="/users"> Users</A><Routes/></>);}render(()=>(<Router><App/></Router>),document.getElementById("app"));
Voby Router provides a number of primitives that read off the Router and Route context.
Retrieves an object containing the route path parameters as defined in the Route.
constparams=useParams();// fetch user based on the id path parameterconst[user]=createResource(()=>params.id,fetchUser);
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 tolocation.state
Note: The state is serialized using thestructured clone algorithm which does not support all object types.
constnavigate=useNavigate();if(unauthorized){navigate("/login",{replace:true});}
Retrieves reactivelocation object useful for getting things likepathname
constlocation=useLocation();constpathname=useComputed(()=>parsePath(location.pathname));
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 andnull 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 asnavigate and auto-scrolling is disabled by default.
const[searchParams,setSearchParams]=useSearchParams();return(<div><span>Page:{searchParams.page}</span><buttononClick={()=>setSearchParams({page:searchParams.page+1})}>Next Page</button></div>);
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.
constuser=useRouteData();return<h1>{user().name}</h1>;
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.
constmatch=useMatch(()=>props.href);return<divclassList={{active:Boolean(match())}}/>;
Used to define routes via a config object instead of JSX. SeeConfig Based Routing.
About
The official client-side router.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors3
Uh oh!
There was an error while loading.Please reload this page.