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:
- Using the <Link> Component
- Using the useRouter hook
<Link> Component
You can use it by importing it from path where your <Link> is exported from, and passing a href
prop to the component:
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:
Checking Active Links
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:
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.
useRouter()
hook
The useRouter
hook allows you manipulate with current URL.
For a full list of useRouter
methods, see the API reference.
Recommendation: Use the <Link>
component to navigate between routes unless you have a specific requirement for using useRouter
.