In Next.js, next/link component enables client-side navigation between pages, enhancing performance by prefetching linked pages. It simplifies routing in your application, making it seamless and efficient.
Next.js next/link Component
The next/link is a Next.js component that allows you to create links between pages in a Next.js application. Unlike a regular HTML anchor tag, next/link does not trigger a full page reload when the user clicks on the link. Instead, it uses client-side navigation to load the new page while preserving the current state of the application. This means that your application will feel faster and more responsive to users.
Syntax:
The syntax for using Link is straightforward. You can import the component from the next/link module:
// Import the component
import Link from 'next/link';
// Link component
<Link href="/https/www.geeksforgeeks.org/page">New Page</Link>
Props:
Prop | Example | Type |
---|
href | href="/https/www.geeksforgeeks.org/page" | String or Object |
replace | replace={false} | Boolean |
scroll | scroll={false} | Boolean |
prefetch | prefetch={false} | Boolean |
Then, you can use the Link component in your JSX code to create a link to another page. The href prop specifies the URL of the page you want to link to, and the child element of the Link component is the content of the link.
Step to Create NextJS Application
Open a terminal or command prompt and run the following command
npx create-next-app next-link
Navigate to your app/project directory:
cd next-link
Project Structure:
NextJs next/linkBasic usage of 'next/link'
In this example, we will create a simple Next.js application with two pages: home and about. We will use next/link to create a link between the pages.
Create a new directory called pages in the root of your project. This is where you will store your Next.js pages. Create a new file called index.js inside the pages directory. This will be the home page of your application. Add the following code to index.js:
JavaScript
// Filename: index.js
import Link from 'next/link';
export default function Home() {
return (
<div>
<h1>Welcome to my Next.js app!</h1>
<Link href="/about">About Us</Link>
</div>
);
}
Create a new file called about.js inside the pages directory.Â
JavaScript
// Filename: about.js
import Link from 'next/link';
export default function About() {
return (
<div>
<h1>About Us</h1>
<p>We are a small team of developers.</p>
<Link href="/">Home</Link>
</div>
);
}
Run the app or development server using the command:
npm run dev
Open your web browser and navigate to http://localhost:3000. You should see the home page of your application with a link to the about page. Click on the link to navigate to the about page. You should see the about page with a link back to the home page.
Output:
NextJs next/linkIn this example, we created a basic Next.js application with two pages and a link between them. We imported the Link component from next/link and used it to create a link to the about page. When the user clicks on the link, Next.js uses client-side navigation to load the about page without triggering a full page reload.
Dynamic routing with 'next/link'
In this example, we will create a Next.js application with dynamic routing using next/link. Create a new file called blog/[slug].js inside the pages directory. This file will be used to display individual blog posts.Â
JavaScript
// Filename: blog/[slug].js
import { useRouter } from 'next/router';
import Link from 'next/link';
export default function BlogPost() {
const router = useRouter();
const { slug } = router.query;
return (
<div>
<h1>{slug}</h1>
<p>This is a blog post with the slug {slug}.</p>
<Link href='/'>Go to Home</Link>
</div>
);
}
JavaScript
// Filename: index.js
import Link from 'next/link';
const posts = [
{ slug: 'post-1', title: 'Post 1' },
{ slug: 'post-2', title: 'Post 2' },
{ slug: 'post-3', title: 'Post 3' },
];
export default function Home() {
return (
<div>
<h1>Welcome to my Next.js app!</h1>
<ul>
{posts.map(post => (
<li key={post.slug}>
<Link href={`/blog/${post.slug}`}>
{post.title}
</Link>
</li>
))}
</ul>
</div>
);
}
Run the development server using the command:
npm run dev
Open your web browser and navigate to http://localhost:3000. You should see the home page of your application with a list of blog posts. Click on one of the links to navigate to the individual post page. You should see the blog post with the corresponding slug in the URL.
Output:
NextJs next/linkIn this example, we demonstrated how to use next/link with dynamic routing. We created a new page template for individual blog posts and used Link to create links to each individual post page. We also used the useRouter hook from next/router to access the slug parameter from the URL and display the corresponding blog post.
Conclusion
The next/link component in Next.js makes navigating between pages smoother by improving client-side rendering with smart prefetching. Its user-friendly syntax and seamless integration simplify linking pages and managing dynamic routes, greatly enhancing the overall user experience in web applications.
Similar Reads
Next.js next/amp
AMP (Accelerated Mobile Pages) is a web component framework developed by Google that enables the creation of fast-loading web pages. Next.js supports AMP out of the box, allowing you to create AMP pages seamlessly.What is Next.js AMP?AMP is designed to improve the performance of web pages, particula
3 min read
Next.js next/head
In this article, we'll learn about the Head component in NextJS and see how the head component is SEO friendly. The Head component is a built-in component provided by NextJS. We can add any element like we were adding in the head component of HTML. If you know HTML and CSS well then NextJS will be e
4 min read
Next.js vs Nuxt.js
Frameworks and libraries are constantly evolving to meet the needs of developers and businesses. Two of the most popular frameworks for building server-side rendered (SSR) applications are Next.js and Nuxt.js. Both frameworks offer great features and capabilities, but they cater to different ecosyst
4 min read
Next.js ESLint
ESLint is a widely-used tool for identifying and fixing problems in JavaScript code. In Next.js projects, integrating ESLint helps ensure code quality and consistency by enforcing coding standards and catching errors early in the development process.In this article, we'll explore how to set up ESLin
3 min read
Next.js Link Component
The Link component in Next.js is used to navigate between pages in a Next.js application. It enables client-side navigation, which provides a smoother user experience by avoiding full-page reloads. This component is crucial for building Single Page Applications with Next.js, as it allows for efficie
2 min read
Next.js Layouts
Layouts in Next.js allow you to create reusable structures that can be shared across multiple pages. This ensures a consistent look and feel throughout your application while reducing code duplication. Next.js 13 introduced enhanced layout capabilities, allowing for nested and dynamic layouts. In th
6 min read
Next.js Pages
The Next.js Pages are the components used to define routes in the next application. Next.js uses a file-based routing system that automatically maps files in the pages directory to application routes, supporting static, dynamic, and nested routes for seamless web development. In this article, we wil
3 min read
Next.js Create Next App
In Next.js, the create next app command is used to automatically initialize a new NextJS project with the default configuration, providing a streamlined way to build applications efficiently and quickly.System Requirements:Node.js 12.22.0 or laterNPM 6.14.4 or later OR Yarn 1.22.10 or latermacOS, Wi
3 min read
Next.js next.config.js File
The next.config.js file in a Next.js application is a configuration file used to customize and extend the behavior of Next.js. It allows developers to adjust various settings such as routing, environment variables, image optimization, and more to tailor the application to their specific needs.What i
3 min read
Next.js on Vercel
Vercel is the platform created by the team behind Next.js, designed to seamlessly deploy and host Next.js applications. Vercel offers a range of features optimized for Next.js, including automatic static optimization, serverless functions, and edge caching.In this article, we are going to see the fe
2 min read