Bound params
A param that sits at the front of nearly every path, such as a locale or a tenant, is bound once with bindParams. No link has to pass the same value again.
On this page
The binding function
src/links.tsimport { bindParams } from '@k8ordo/router';
import { locales } from './i18n';
export const { href, navigateTo } = bindParams(() => ({
locale: locales.getLocale(),
}));bindParams takes a function that returns the params to bind. The href and navigateTo it returns fill any param the call leaves out with that function’s value.
The app imports href and navigateTo from this module.
Bound links
import { href, navigateTo } from './links';
href('/:locale/products/:id', { id: '42' }); // '/ja/products/42'
href('/:locale', { locale: 'en' }); // '/en'
Pass the bound `locale` to override it
navigateTo('/:locale/products');Patterns keep their full /:locale/… spelling. The bound locale can be left out, so only the other params are passed. The results in the comments are for a current locale of ja.
A link to a page in another locale, such as a language switcher, passes the bound param to override it.
Since the patterns are spelled as before, the Register check still applies. A pattern the table lacks, or a missing param that is not bound, is a type error.
The locale param
src/components/docs-link.tsximport { useMatch } from '@k8ordo/router';
import { href } from '../links';
export function DocsLink() {
const inDocs = useMatch('/:locale/docs/*') !== null;
return (
<a aria-current={inDocs ? 'page' : undefined} href={href('/:locale/docs')}>
Docs
</a>
);
}locales.getLocale() comes from @k8ordo/i18n. The locale it returns is described on Current locale.
useMatch also takes a pattern with the locale still in it, such as /:locale/docs/*. The locale matches as the :locale param, so it matches on every language’s page alike.
When the function runs
The binding function runs every time href or navigateTo is called. A value that differs per request or per URL is taken at the moment the link is built.
Calling bindParams once at the top level of a module is enough.
Which package supplies the value is up to the app. The router knows only the param’s name.
Options position
navigateTo('/:locale', undefined, { history: 'replace' });
Pass `undefined` in place of the params
navigateTo('/:locale', { locale: 'en' }, { history: 'replace' });
navigateTo('/:locale', { history: 'replace' });
Options in second place are a type errorEven for a pattern whose params are all bound, navigateTo’s options are the third argument.
When the pattern names a param, the second argument is always read as params.
Pitfall
If a type assertion lets options through as the second argument, they are read as params. history is ignored, and a new history entry is added.