Client-side transitions between routes may be made easier with the Link component imported from the next/link module.
Take the following files from a home directory as an example:
/home/index.js or /home
/home/about.js
/home/blog/[blog_slug].js
We may create a link to each of these pages in the following format
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import Link from 'next/link'
function HomePage() {
return (
<ul>
<li>
<Link href="/">
<a> Home Page </a>
</Link>
</li>
<li>
<Link href="/about">
<a> About Us Page </a>
</Link>
</li>
<li>
<Link href="/blog/page">
<a> Blog Page </a>
</Link>
</li>
</ul>
)
}
export default HomePage
The following props are accepted by Link
href - The URL or route to which you want to go. This is the only prop that is necessary.
as - An optional decorator for the path that will appear in the URL bar of the browser. This was utilized for dynamic routes before Next. js 9.5.3.
Note that if this path is different from the one specified in the href prop, the prior href/as behavior is used, as described in the previous documentation.
passHref - Forces to convey the href property to its child, use this link. False is the default value.
prefetch - To fetch pages earlier in the background. True is the default value. Any content that is currently in the viewport (either by default or by scrolling) will be preloaded. By specifying the value of the prefetch prop to false, prefetching can be turned off. Prefetching will still happen on hover even if prefetch is set to false. For speedier page transitions, pages employing Static Generation will preload JSON files containing the data. Prefetching is only available in the production environment.
replace - Instead of adding a new URL to the stack, it replaces the current history state. False is the default value.
scroll - After navigation, it scrolls to the top of the page. True is the default value.
shallow - Updates the current page’s route without reloading it. getStaticProps, getServerSideProps or getInitialProps are some of the methods available. The default value is false.
Note: We’re not covering shallow routing in this article because it’s off the topic. If you want to learn more about it you can follow the link included above.
locale - The active locale is prefixed automatically. It is possible to provide a different locale using a locale. The default behavior is deactivated when the false href has to contain the locale.
Since the release of Next.js 9.5.3, there is no need to do anything when connecting to a dynamic route, including catch-all routes (for older versions check the previous docs of Next.js). Using interpolation or a URL Object to create the link, on the other hand, can become extremely frequent and useful.
The dynamic route home/blog/[board_slug].js, for example, will match this URL.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import Link from "next/link";
function Blogs({
blogs
}) {
return (
<ul>
{blogs.map((blog) => (
<li key={blog.id}>
<Link href={`/blog/{encodeURIComponent(blog.slug)}`}>
<a>{blog.title}</a>
</Link>
</li>
))}
</ul>
);
}
export default Blogs;
You must pass passHref prop to Link if its child is a custom element that encapsulates an anchor tag. If you’re going to use styled-components you’ll need to do this. The href attribute will be missing from the <a>
element if you don’t do this, which will make your site less accessible and may have an impact on SEO. If you are using ESLint, you may use the next/link-passhref rule to guarantee that passHref is used correctly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import Link from 'next/link'
import styled from 'styled-components'
// This will create <a> tag wrapped by a custom component
const ColorLink = styled.a`color: blue;`
function NavigationLink({
link_name,
link_href
}) {
// Passing passHref prop is mandatory
return (
<Link href={ link_href } passHref>
<ColorLink>{ link_name }</ColorLink>
</Link>
)
}
export default NavigationLink
Even if you use an <a>
tag directly, you must use passHref if you are utilizing the JSX pragma characteristic property (@jsx jsx) of emotion.
To properly activate navigation, the component should support the onClick attribute.
If the Link’s child is a functional element, you must wrap it with React.forwardRef in addition to using passHref like given below
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import Link from 'next/link'
// For proper handling ref, href, and onClick must be
// passed to the DOM element
const LinkButton = React.forwardRef(({
onClick,
href
}, ref) => {
return (
<a href={href} onClick={onClick} ref={ref}>
Click Here
</a>
)
})
function HomeComponent() {
return (
<Link href='/about' passHref>
<LinkButton/>
</Link>
)
}
export default HomeComponent
The Link may also take a URL object & format it into a URL string for you. How to accomplish it is as follows
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import Link from 'next/link'
function HomeComponent() {
return (
<ul>
<li>
<Link
href={{
pathname: '/about',
query: { source: 'search' },
}}
>
<a> About Us </a>
</Link>
</li>
<li>
<Link
href={{
pathname: '/blog/[board_slug]',
query: { slug: 'my-blog' },
}}
>
<a> My Blog Post </a>
</Link>
</li>
</ul>
)
}
export default HomeComponent
The example given above includes a link to –
/about?source=search is a preset route.
/blog/my-blog is a dynamic route.
Every attribute described in the URL module documentation of Node.js can be used.
The default behavior of the Link component is to push a new URL into the history stack of the props. You can use the replace prop to prevent adding a new entry, as given in the following example.
1 2 3
<Link replace href="/about"> <a> About Us </a> </Link>
Link’s default behavior is to scroll all the way to the top of the page. When a hash is defined, it scrolls to the specified ID, just like a conventional anchor tag. To avoid scrolling to the top, or element with ID by using the hash route (by default we can scroll to element with ID, say ‘name’ by giving value ‘#name’ to href of the anchor tag), pass the false value to the scroll prop of Link as given as follows
1 2 3
<Link href="#hash_id" scroll={false}> <a> Disables scrolling to the top, or element</a> </Link>
To prevent downloading unneeded content, set the prefetch attribute on <Link>
to false to deactivate prefetching for infrequently visited pages as given as follows
1 2 3
<Link href="/about" prefetch={false}> <a> About Us </a> </Link>
To come up with a new locale other than the one presently active, a locale prop can be used. During client transitions the currently operating locale is utilized if no locale parameter is specified. Consider the following scenario
1 2 3
<Link href="/another" locale="fr"> <a> to france locale </a> </Link>