Rocon Website

Dynamic Routes and Matching

Not all routes are static; a common situation is that we want to define routes like /:id/profile where any string is allowed to fill the :id segment.

To handle this situation, the Path route builder provides an any method to define a catch-all route. In the next example a builder with a catch-all route is defined. Visiting /uhyo should result in Hello, uhyo and visiting /Pikachu should result in Hello, Pikachu. If both the any route and other normal routes are defined, normal routes take precedence.

const toplevelRoutes = Rocon.Path()
  .any("id", {
    action: ({ id }) => <p>Hello, {id}</p>
  });

The first argument passed to any is a match key. A match key is the name of a property of the match object, which is the object that stores variable parts of URLs. In the case of the above example, any path segment is catched by the any route and the segment is stored in the id property of the match object.

A match object is passed to the action function so that it can be used to render contents of the any route. Of course, all the process is type-safe; the id property of the match object is only available under the corresponding any route.

Attaching to the any route

By attaching another route to the any route, paths like /:id/profile are realized.

A Path route builder with an any route has a anyRoute property which is the route record of the any route. Thus, you can define /:id/profile as follows:

const toplevelRoutes = Rocon.Path()
  .any("id");

const userRoutes = toplevelRoutes.anyRoute
  .attach(Rocon.Path())
  .route("profile", (route) => route.action(({ id }) =>
    <p>Your ID is {id}</p>
  ));