<Link>
is a React component that extends the HTML <a>
element to provide prefetching and client-side navigation between routes. It is the primary way to navigate between routes in Next.js.
import Link from 'next/link';
export default function Page() {
return <Link href="/dashboard">Dashboard</Link>;
}
Here's a summary of the props available for the Link Component:
Prop | Example | Type | Required |
---|---|---|---|
href | href="/dashboard" | String or Object | Yes |
replace | replace={false} | Boolean | - |
prefetch | prefetch={false} | Boolean | - |
Good to know:
<a>
tag attributes such asclassName
ortarget="_blank"
can be added to<Link>
as props and will be passed to the underlying<a>
element.
href
(required)The path or URL to navigate to.
<Link href="/dashboard">Dashboard</Link>
href
can also accept an object, for example:
// Navigate to /about?name=test
<Link
href={{
pathname: '/about',
query: { name: 'test' },
}}
>
About
</Link>
replace
Defaults to false
. When true
, next/link
will replace the current history state instead of adding a new URL into the browser’s history stack.
import Link from 'next/link';
export default function Page() {
return <Link href="/dashboard" replace>Dashboard</Link>;
}
prefetch
Defaults to true
. When true
, next/link
will prefetch the page (denoted by the href
) in the background. This is useful for improving the performance of client-side navigations. Any <Link />
in the viewport (initially or through scroll) will be preloaded.
Prefetch can be disabled by passing prefetch={false}
. Prefetching is only enabled in production.
import Link from 'next/link';
export default function Page() {
return <Link href="/dashboard" prefetch={false}>Dashboard</Link>;
}
as
: The concept of masking URLs in the app
directory will be handled with advanced routing patterns (more documentation soon). For compatibility with old dynamic routes in the pages
directory, you can pass as
prop to Link
. However, since you can now pass dynamic segments to the href
prop, using as
is not recommended in the app
directory.legacyBehavior
: An <a>
element is no longer required as a child of <Link>
. Add the legacyBehavior
prop to use the legacy behavior or remove the <a>
to upgrade. A codemod is available to automatically upgrade your code.passHref
: Not necessary as <Link>
will render an underlying <a>
element with the correct href
. This includes cases for:<Link href="/about">About</Link>
<Link href="/about"><CustomComponent /></Link>
<Link href="/about"><strong>About</strong></Link>