Relative navigation
The href
attribute of a Link, the action
attribute of a Form, and the to
parameter to the navigate function
all specify the target url of a navigation.
By default, relative targets are relative to the path of the route that does the navigation.
import Routes, { Link } from 'react-sprout';
let Router = Routes(
<App>
<Admin path="admin">
<Tags path="tags" />
<Tag path="tags/:tagId" />
</Admin>
</App>,
);
function Admin(props) {
return (
<main>
<h1>Admin</h1>
<nav>
<Link href="tags">Tags</Link>
</nav>
<section>{props.children}</section>
</main>
);
}
The Link element that is rendered by the Admin route component uses a relative target tags
.
It will always resolve to /admin/tags
as all relative targets inside the Admin route component will be relative to /admin
.
This makes relative navigation predictable as they always resolve to the same url, regardless of the current url.
This "route relative" behavior can be disabled by setting relative
to false
, causing navigation targets to be relative to the current url instead.
function Admin(props) {
return (
<main>
<h1>Admin</h1>
<nav>
<Link href=".." relative={false}>
Up
</Link>
</nav>
<section>{props.children}</section>
</main>
);
}
This will make the target url of the Link dependent on the current url:
- When the current url is
/admin/tags
, the Link would refer to/admin
. - When the current url is
/admin/tags/1
, the Link would refer to/admin/tags
.
If you ever need to resolve paths in the same way the router does, without actually navigating, there is a useResolve hook to do just that.
import { useResolve } from 'react-sprout'
function UpLink(props) {
let resolve = useResolve()
let href = resolve('..', { relative: false })
return <a href={href}>Up</a>
}