Docs
Linking and Navigating

Linking and Navigating

This page will go through how to use each of these options, and dive deeper into how navigation works.

There are four ways to navigate between routes in Another react router:

You can use it by importing it from path where your <Link> is exported from, and passing a href prop to the component:

/src/routes/page.tsx
import { Link } from "@/components/link"
 
export default function Page() {
	return <Link href="/dashboard">Dashboard</Link>
}

There are other optional props you can pass to <Link>. See the API reference for more.

Examples

Linking to Dynamic Segments

When linking to dynamic segments, you can use template literals and interpolation to generate a list of links. For example, to generate a list of blog posts:

/src/routes/blog/PostList.tsx
import { Link } from "@/components/link"
 
export default function PostList({ posts }) {
	return (
		<ul>
			{posts.map(post => (
				<li key={post.id}>
					<Link href={`/blog/${post.slug}`}>{post.title}</Link>
				</li>
			))}
		</ul>
	)
}

You can use usePathname() to determine if a link is active. For example, to add a class to the active link, you can check if the current pathname matches the href of the link:

/src/components/ui/nav-links.tsx
import { usePathname } from "another-react-router"
import { Link } from "@/components/link"
 
export function Links() {
	const pathname = usePathname()
 
	return (
		<nav>
			<Link className={`link ${pathname === "/" ? "active" : ""}`} href="/">
				Home
			</Link>
 
			<Link
				className={`link ${pathname === "/about" ? "active" : ""}`}
				href="/about"
			>
				About
			</Link>
		</nav>
	)
}

Scrolling to an id

If you'd like to scroll to a specific id on navigation, you can append your URL with a # hash link or just pass a hash link to the href prop.

<Link href="/dashboard#settings">Settings</Link>

useRouter() hook

The useRouter hook allows you manipulate with current URL.

/src/routes/page.tsx
import { useRouter } from "another-react-router"
 
export default function Page() {
	const router = useRouter()
 
	return (
		<button type="button" onClick={() => router.push("/dashboard")}>
			Dashboard
		</button>
	)
}

For a full list of useRouter methods, see the API reference.