Links
To let people move between pages, use <Link>:
import { Link } from "./routes";
<Link href="/players/9" className="navlink">Player 9</Link>;
A plain left click navigates instantly — no page reload — and everything else about it behaves like a normal link.
It's a real <a href>
Link renders an actual anchor, not a <span> with a click handler, and that
matters:
- ⌘/Ctrl-click and middle-click open a new tab (the browser handles them);
- right-click → copy link address works;
- search engines follow it, which is much of how a site gets found;
- hovering shows the destination in the status bar.
A plain left click is caught and routed through the router (instant); anything else is left to the browser.
A query and a hash
A path may carry a query and a hash. push takes the same:
import { Link } from "./routes";
const sortedBy = (key: string) => <Link href={`/players?sort=${encodeURIComponent(key)}#top`}>By {key}</Link>;
The path before the ? is checked against your route table, to the letter; what follows it is
not. A query needs at least one key=value. A value from data goes through encodeURIComponent,
so a space, an & or a # in it stays part of the value.
A path and a query, or a :param? A :param route — /players/:id — is one page per id, and
each can be baked at build time when the ids are known then. When they are not —
an id the reader created, stored only in their browser — a fixed path with the id in the query,
/player?id=…, is one page, baked once. The baked page has no query, so what it shows for the id
comes after the page loads: a clientOnly query keyed by
the id renders pending on the server and on the client's first render alike.
Props
replace— replace the history entry instead of adding one.scroll— scroll to the top after navigating. Defaults totrue(a link is a real navigation); passscroll={false}for a link that swaps a view in place, like tabs partway down a long page.
What it leaves to the browser
Link does not intercept:
- a click with a modifier key, or a non-primary button;
target="_blank"or adownload;- a link to another site (a different origin is a different app);
- a click something else already called
preventDefault()on.
Navigating from code instead
Sometimes a navigation is the result of an action, not a link someone clicks — a
redirect after saving. For that, use the router's push (next page):
import { Navigator } from "./routes";
export class SaveButton extends Component<{ onSave: () => Promise<void> }> {
route = this.use(Navigator);
async save() {
await this.props.onSave();
this.route.push("/done");
}
}
Rule of thumb: if a person should be able to open it in a new tab, it is a <Link>.
If it is a consequence of something else, it is push.
Next
- Params, query and hash — reading the URL.