-
Notifications
You must be signed in to change notification settings - Fork 0
Routing
Cardboard offers a very simple option for adding routing to your app.
Take a look at the router example for a real example.
It's very simple to create a router:
import { makeRouter, router, Link } from 'cardboard-js/dist/ext/routing.js';
const myRouter = makeRouter({
rootParent: tag('(body)'),
routes: {
'/': (_) => HomeRoute(),
'/home': '/', // Alias from /home to /
'/about': (_) => AboutRoute(),
'/user/:id': (_) => UserRoute(),
'/404': (router) => div('404: Route not found: ' + router.currentRoute),
},
initialRoute: '/',
fallbackRoute: '/404'
});
-
rootParent
will be the element onto which the router will add/remove the routes. -
routes
accept a function that returns a CTag. -
initialRoute
initial route to load -
fallbackRoute
fallback route if navigating to a route that does not exist
makeRouter
returns a Router
. With the router, you can navigate
to routes and get the currentRoute
.
Additionally, you can also get the router by importing router
. Or you can use the component Link
for simpler navigation.
myRouter.navigate('/home');
router.navigate('/user/1234');
Link('About', '/about');
Routes can define params (:param
) in the routes definitions. These parameters are available inside the router router.params
.
makeRouter({
routes: {
'/user/:id': (_) => UserRoute(),
}
});
This will match:
/user/123
/user/234
/user/bob
But not:
/user
/user/bob/test
Then when you want to consume the parameters:
const userId = router.query.get('id');
You can also get query parameters with the router.query
, and set them when navigating
router.navigate('/user/test', { hideBanner: 'true' });
const hideBanner = router.query.get('hideBanner');
This Wiki is a work in progress, it's just me doing everything around here :P
If you read this and have some free time, and want to spend it helping me with the wiki or anything else, you're more than welcome!