Skip to content

Routing

Manolo Edge edited this page Oct 28, 2023 · 6 revisions

Cardboard offers a very simple option for adding routing to your app.

Take a look at the router example for a real example.

Basic Usage

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');

Params

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');

Query Parameters

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');