Rocon Website

Query Parameters

Query parameters, also known as location.search, are the parts of URL preceded by a ? mark. One parameter is a key-value pair of the form key=value.

To retrieve information from query parameters, we use a Search route builder. If the /foo route requires a query parameter named name, we create a Search route builder for the name query and attach it to the /foo route. The value of the name query can be retrieved from the match object.

const toplevelRoutes = Rocon.Path()
  .route("foo")
  .route("bar", (route) => route.action(() => <p>This is bar</p>));

const fooRoute = toplevelRoutes._.foo
  .attach(Rocon.Search("name"))
  .action(({ name }) => <p>This is foo, your name is {name}</p>);

As demonstrated above, a Search route builder has an action method to define an action for that route. With this set up, by visiting /foo?name=uhyo you will see This is foo, your name is uhyo. If name query parameter is not provided, a LocationNotFoundError is thrown.

Optional Query Parameter

If you want the query parameter to be optional, set the optional option to true. By setting the optional flag, the type of name in the match object becomesstring | undefined, not string.

const toplevelRoutes = Rocon.Path()
  .route("foo")
  .route("bar", (route) => route.action(() => <p>This is bar</p>));

const fooRoute = toplevelRoutes._.foo
  .attach(Rocon.Search("name", { optional: true }))
  .action(({ name }) => <p>This is foo, your name is {name}</p>);

Specifying a Different Search Key

As shown above, the first parameter of Search is treated both as a search query key and also as a match key (key of the match object). The match key is always the first paramter, and you can use a searchKey option to use a different string as a search key.

const toplevelRoutes = Rocon.Path()
  .route("foo")
  .route("bar", (route) => route.action(() => <p>This is bar</p>));

const fooRoute = toplevelRoutes._.foo
  .attach(Rocon.Search("name", { searchKey: "yourname" }))
  .action(({ name }) => <p>This is foo, your name is {name}</p>);

With this setting, fooRoute now expresses a URL like /foo?yourname=uhyo.

Navigating to a Route with Query Parameter

Of course, to navigate to a route with query parameters, you have to provide a match object. A route record of a Search path builder is available via its route property.

navigate(fooRoute.route, { name: "Pikachu" });

Multiple Query Parameters

One Search route builder supports only one query parameter. To define more than one query parameter for the same route, attach another Search route builder to that route.

const fooRoute = toplevelRoutes._.foo
  .attach(Rocon.Search("name", { searchKey: "yourname" }))
  .attach(Rocon.Search("age", { optional: true }))
  .action(({ name, age }) => <p>This is foo, your name is {name} and your age is {age}</p>);