Links

Build links that put a definition’s state on the URL the router built. The query leaves defaults out.

On this page

href

ts
import { href } from '@k8ordo/router';

listState.href(href('/products'));
// '/products'

listState.href(href('/products'), { inStock: true, page: 2 });
// '/products?inStock=true&page=2'

listState.href('', { page: 2 });
// '?page=2'

href(url, values?) puts the definition’s state on the URL it is given. A field you leave out means its default, and a field at its default is left out of the query. The shape of the URL it builds is described on URL.

Pass url a URL href of @k8ordo/router returned, or a Next.js Route. Given '', it returns a link relative to the page, such as ?page=2. The browser reads that as replacing the page’s whole query, so use it for display or for a link that keeps nothing else of the query.

The return type keeps the URL you passed as a literal. When that URL already carries the definition’s params or a fragment, the type is an approximation: those params are rewritten, and the query goes in before the fragment. An entry-only definition returns the URL as given. A value the field’s kind cannot write throws an error containing cannot write to a URL or cannot write to a fragment.

For the one way to write every other URL, from a link to a page to a page change from code, see Links and navigation.

Other params

ts
const url = campaignState.href(href('/products'), { ref: 'mail' });
// '/products?ref=mail'

listState.href(url, { page: 2 });
// '/products?ref=mail&page=2'

productState.href(href('/products/:id', { id: 42 }), {
  hash: 'reviews',
});
// '/products/42#reviews'

Only the definition’s own url params are rewritten. The URL’s other params, such as the ref another definition put there in the example, stay as they are spelled, and the definition’s params follow them. It is the same rule update() follows when it writes the URL.

A definition with a hash slot sets the fragment to the value of values.hash, and drops it at the default. A definition without one keeps the URL’s own fragment.

Vite’s base

ts
listState.href(href('/products'), { page: 2 });
// '/docs/products?page=2'

href adds nothing to the path. href of @k8ordo/router has already put Vite’s base in front, so under base: '/docs/' the link is '/docs/products?page=2'. Next.js’s own <Link> adds its basePath.

Typed paths

tsx
import Link from 'next/link';

<Link href={listState.href('/products', { page: 2 })}>next</Link>;

The pattern is type-checked by href of @k8ordo/router, which builds the URL. A pattern missing from the table, or a missing param, is a type error there, and there is nothing to register with this package. See Typed paths.

In Next.js, pass the Route path as it is. The return type keeps that path, so <Link>’s typed-route check still applies.

k8ordo

React libraries that use Baseline features without holding back.