)
}
```
```jsx filename="app/blog/post-list.js" switcher
import Link from 'next/link'
export default function PostList({ posts }) {
return (
{posts.map((post) => (
{post.title}
))}
)
}
```
### Checking active links
You can use [`usePathname()`](/docs/app/api-reference/functions/use-pathname) 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:
```tsx filename="app/ui/nav-links.tsx" switcher
'use client'
import { usePathname } from 'next/navigation'
import Link from 'next/link'
export function Links() {
const pathname = usePathname()
return (
)
}
```
```jsx filename="app/ui/nav-links.js" switcher
'use client'
import { usePathname } from 'next/navigation'
import Link from 'next/link'
export function Links() {
const pathname = usePathname()
return (
)
}
```
### Linking to dynamic route segments
For [dynamic route segments](/docs/pages/building-your-application/routing/dynamic-routes#convention), it can be handy to use template literals to create the link's path.
For example, you can generate a list of links to the dynamic route `pages/blog/[slug].js`
```tsx filename="pages/blog/index.tsx" switcher
import Link from 'next/link'
function Posts({ posts }) {
return (
{posts.map((post) => (
{post.title}
))}
)
}
```
```jsx filename="pages/blog/index.js" switcher
import Link from 'next/link'
function Posts({ posts }) {
return (
)
}
export default Home
```
```jsx filename="pages/index.js" switcher
import Link from 'next/link'
function Home() {
return (
About us
Blog Post
)
}
export default Home
```
The above example has a link to:
- A predefined route: `/about?name=test`
- A [dynamic route](/docs/pages/building-your-application/routing/dynamic-routes#convention): `/blog/my-post`
You can use every property as defined in the [Node.js URL module documentation](https://nodejs.org/api/url.html#url_url_strings_and_url_objects).
### Replace the URL instead of push
The default behavior of the `Link` component is to `push` a new URL into the `history` stack. You can use the `replace` prop to prevent adding a new entry, as in the following example:
```tsx filename="app/page.js" switcher
import Link from 'next/link'
export default function Page() {
return (
About us
)
}
```
```jsx filename="app/page.js" switcher
import Link from 'next/link'
export default function Page() {
return (
About us
)
}
```
```tsx filename="pages/index.js" switcher
import Link from 'next/link'
export default function Home() {
return (
About us
)
}
```
```jsx filename="pages/index.js" switcher
import Link from 'next/link'
export default function Home() {
return (
About us
)
}
```
### Disable scrolling to the top of the page
The default scrolling behavior of `` in Next.js **is to maintain scroll position**, similar to how browsers handle back and forwards navigation. When you navigate to a new [Page](/docs/app/api-reference/file-conventions/page), scroll position will stay the same as long as the Page is visible in the viewport.
However, if the Page is not visible in the viewport, Next.js will scroll to the top of the first Page element. If you'd like to disable this behavior, you can pass `scroll={false}` to the `` component, or `scroll: false` to `router.push()` or `router.replace()`.
```jsx filename="app/page.js" switcher
import Link from 'next/link'
export default function Page() {
return (
Disables scrolling to the top
)
}
```
```tsx filename="app/page.tsx" switcher
import Link from 'next/link'
export default function Page() {
return (
Disables scrolling to the top
)
}
```
Using `router.push()` or `router.replace()`:
```jsx
// useRouter
import { useRouter } from 'next/navigation'
const router = useRouter()
router.push('/dashboard', { scroll: false })
```
The default behavior of `Link` is to scroll to the top of the page. When there is a hash defined it will scroll to the specific id, like a normal `` tag. To prevent scrolling to the top / hash `scroll={false}` can be added to `Link`:
```jsx filename="pages/index.js" switcher
import Link from 'next/link'
export default function Home() {
return (
Disables scrolling to the top
)
}
```
```tsx filename="pages/index.tsx" switcher
import Link from 'next/link'
export default function Home() {
return (
Disables scrolling to the top
)
}
```
### Prefetching links in Middleware
It's common to use [Middleware](/docs/app/api-reference/file-conventions/middleware) for authentication or other purposes that involve rewriting the user to a different page. In order for the `` component to properly prefetch links with rewrites via Middleware, you need to tell Next.js both the URL to display and the URL to prefetch. This is required to avoid un-necessary fetches to middleware to know the correct route to prefetch.
For example, if you want to serve a `/dashboard` route that has authenticated and visitor views, you can add the following in your Middleware to redirect the user to the correct page:
```ts filename="middleware.ts" switcher
import { NextResponse } from 'next/server'
export function middleware(request: Request) {
const nextUrl = request.nextUrl
if (nextUrl.pathname === '/dashboard') {
if (request.cookies.authToken) {
return NextResponse.rewrite(new URL('/auth/dashboard', request.url))
} else {
return NextResponse.rewrite(new URL('/public/dashboard', request.url))
}
}
}
```
```js filename="middleware.js" switcher
import { NextResponse } from 'next/server'
export function middleware(request) {
const nextUrl = request.nextUrl
if (nextUrl.pathname === '/dashboard') {
if (request.cookies.authToken) {
return NextResponse.rewrite(new URL('/auth/dashboard', request.url))
} else {
return NextResponse.rewrite(new URL('/public/dashboard', request.url))
}
}
}
```
In this case, you would want to use the following code in your `` component:
```tsx filename="app/page.tsx" switcher
'use client'
import Link from 'next/link'
import useIsAuthed from './hooks/useIsAuthed' // Your auth hook
export default function Page() {
const isAuthed = useIsAuthed()
const path = isAuthed ? '/auth/dashboard' : '/public/dashboard'
return (
Dashboard
)
}
```
```js filename="app/page.js" switcher
'use client'
import Link from 'next/link'
import useIsAuthed from './hooks/useIsAuthed' // Your auth hook
export default function Page() {
const isAuthed = useIsAuthed()
const path = isAuthed ? '/auth/dashboard' : '/public/dashboard'
return (
Dashboard
)
}
```
```tsx filename="pages/index.tsx" switcher
'use client'
import Link from 'next/link'
import useIsAuthed from './hooks/useIsAuthed' // Your auth hook
export default function Home() {
const isAuthed = useIsAuthed()
const path = isAuthed ? '/auth/dashboard' : '/public/dashboard'
return (
Dashboard
)
}
```
```js filename="pages/index.js" switcher
'use client'
import Link from 'next/link'
import useIsAuthed from './hooks/useIsAuthed' // Your auth hook
export default function Home() {
const isAuthed = useIsAuthed()
const path = isAuthed ? '/auth/dashboard' : '/public/dashboard'
return (
Dashboard
)
}
```
> **Good to know**: If you're using [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes#convention), you'll need to adapt your `as` and `href` props. For example, if you have a Dynamic Route like `/dashboard/authed/[user]` that you want to present differently via middleware, you would write: `Profile`.
### Blocking navigation
You can use the `onNavigate` prop to block navigation when certain conditions are met, such as when a form has unsaved changes. When you need to block navigation across multiple components in your app (like preventing navigation from any link while a form is being edited), React Context provides a clean way to share this blocking state. First, create a context to track the navigation blocking state:
```tsx filename="app/contexts/navigation-blocker.tsx" switcher
'use client'
import { createContext, useState, useContext } from 'react'
interface NavigationBlockerContextType {
isBlocked: boolean
setIsBlocked: (isBlocked: boolean) => void
}
export const NavigationBlockerContext =
createContext({
isBlocked: false,
setIsBlocked: () => {},
})
export function NavigationBlockerProvider({
children,
}: {
children: React.ReactNode
}) {
const [isBlocked, setIsBlocked] = useState(false)
return (
{children}
)
}
export function useNavigationBlocker() {
return useContext(NavigationBlockerContext)
}
```
```jsx filename="app/contexts/navigation-blocker.js" switcher
'use client'
import { createContext, useState, useContext } from 'react'
export const NavigationBlockerContext = createContext({
isBlocked: false,
setIsBlocked: () => {},
})
export function NavigationBlockerProvider({ children }) {
const [isBlocked, setIsBlocked] = useState(false)
return (
{children}
)
}
export function useNavigationBlocker() {
return useContext(NavigationBlockerContext)
}
```
Create a form component that uses the context:
```tsx filename="app/components/form.tsx" switcher
'use client'
import { useNavigationBlocker } from '../contexts/navigation-blocker'
export default function Form() {
const { setIsBlocked } = useNavigationBlocker()
return (
)
}
```
```jsx filename="app/components/form.js" switcher
'use client'
import { useNavigationBlocker } from '../contexts/navigation-blocker'
export default function Form() {
const { setIsBlocked } = useNavigationBlocker()
return (
)
}
```
Create a custom Link component that blocks navigation:
```tsx filename="app/components/custom-link.tsx" switcher
'use client'
import Link from 'next/link'
import { useNavigationBlocker } from '../contexts/navigation-blocker'
interface CustomLinkProps extends React.ComponentProps {
children: React.ReactNode
}
export function CustomLink({ children, ...props }: CustomLinkProps) {
const { isBlocked } = useNavigationBlocker()
return (
{
if (
isBlocked &&
!window.confirm('You have unsaved changes. Leave anyway?')
) {
e.preventDefault()
}
}}
{...props}
>
{children}
)
}
```
```jsx filename="app/components/custom-link.js" switcher
'use client'
import Link from 'next/link'
import { useNavigationBlocker } from '../contexts/navigation-blocker'
export function CustomLink({ children, ...props }) {
const { isBlocked } = useNavigationBlocker()
return (
{
if (
isBlocked &&
!window.confirm('You have unsaved changes. Leave anyway?')
) {
e.preventDefault()
}
}}
{...props}
>
{children}
)
}
```
Create a navigation component:
```tsx filename="app/components/nav.tsx" switcher
'use client'
import { CustomLink as Link } from './custom-link'
export default function Nav() {
return (
)
}
```
```jsx filename="app/components/nav.js" switcher
'use client'
import { CustomLink as Link } from './custom-link'
export default function Nav() {
return (
)
}
```
Finally, wrap your app with the `NavigationBlockerProvider` in the root layout and use the components in your page:
```tsx filename="app/layout.tsx" switcher
import { NavigationBlockerProvider } from './contexts/navigation-blocker'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
{children}
)
}
```
```jsx filename="app/layout.js" switcher
import { NavigationBlockerProvider } from './contexts/navigation-blocker'
export default function RootLayout({ children }) {
return (
{children}
)
}
```
Then, use the `Nav` and `Form` components in your page:
```tsx filename="app/page.tsx" switcher
import Nav from './components/nav'
import Form from './components/form'
export default function Page() {
return (
Welcome to the Dashboard
)
}
```
```jsx filename="app/page.js" switcher
import Nav from './components/nav'
import Form from './components/form'
export default function Page() {
return (