@k8ordo/router

Links and navigation

Build a link’s URL with href from a pattern in the route table and hand it to a plain <a>. To change pages from code, after a button press for instance, use navigateTo.

On this page

Link URLs

ts
href('/products'); // '/products'
href('/products/:id', { id: '42' }); // '/products/42'
href('/products/:id', { id: 42 }); // '/products/42'
href('/products/:id', { id: 'a/b' }); // '/products/a%2Fb'

href builds a URL string from a pattern and its params. A pattern without params takes no second argument.

A param value is a string, a number, a bigint or a boolean. Values are encoded with encodeURIComponent, so one containing / still becomes a single path segment.

The result goes straight into an <a>’s href attribute. When the app is served under a base path, the base path comes first. See Base path.

Information

Note

If a call gets past the type checks, it throws a TypeError at run time in three cases:

  • A pattern containing /*: is a wildcard — it has no href
  • A param without a value: needs a value for ":id"
  • A value with no URL form, such as an object: has no URL spelling

Writing a link

src/product-card.tsx
import { href } from '@k8ordo/router';

type Props = { id: string; name: string };

export function ProductCard({ id, name }: Props) {
  return <a href={href('/products/:id', { id })}>{name}</a>;
}

This router has no <Link> component. Clicking an <a> fires the browser’s navigate event, and the router handles that event and changes the page. href checks the pattern, so links stay plain <a> elements.

A link to another origin, or to a path missing from the route table, is an ordinary page load (see How it works).

To mark the link to the page that is open, use useMatch. See Location.

ts
navigateTo('/products/:id', { id: '42' });
navigateTo('/products/:id', { id: '42' }, { history: 'replace' });
navigateTo('/products');
navigateTo('/products', { history: 'replace' });

navigateTo builds the URL from the same arguments as href and goes to that page. By default it adds a new history entry, so the browser’s back button returns to the previous page.

To replace the current entry instead, pass { history: 'replace' }. For a pattern without params, the options are the second argument.

To change only the state within a page, use @k8ordo/state’s update(). See URL.

Awaiting finished

src/open-button.tsx
import { navigateTo } from '@k8ordo/router';
import { useTransition } from 'react';

const isAbort = (error: unknown) =>
  error instanceof DOMException && error.name === 'AbortError';

export function OpenButton({ id }: { id: string }) {
  const [isPending, startTransition] = useTransition();
  const open = () => {
    startTransition(async () => {
      try {
        await navigateTo('/products/:id', { id }).finished;
      } catch (error) {
        if (!isAbort(error)) throw error;
      }
    });
  };

  return (
    <button disabled={isPending} onClick={open} type="button">
      {isPending ? 'Opening…' : 'Open'}
    </button>
  );
}

navigateTo returns the same { committed, finished } as the Navigation API’s navigation.navigate(). finished resolves once the new page is on screen.

Await finished inside a useTransition action, and isPending is true until the page is on screen.

If another navigation starts while you wait, finished rejects with a DOMException named AbortError. As in the example, ignore the abort and rethrow anything else.

File links

tsx
<a download href="/report.pdf">
  Download the report
</a>

With /* at the end of the route table, the table matches every path. The router then handles a link to a file the host serves too, so opening /report.pdf renders the /* page instead of the file.

With the download attribute, the navigate event’s downloadRequest is no longer null. The router does not handle that event, so the file is saved as is.

Information

Note

Under @k8ordo/framework, download also saves a reload. See Deployment.

k8ordo

React libraries that use Baseline features without holding back.