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
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() {
6 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides DOM-specific methods to interact with and manipulate the Document Object Model (DOM), enabling efficient rendering and management of web page elements. ReactDOM is used for: Rendering Components: Displays React components in the DOM.DOM Manipulation: Al
2 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collectionsâlike user profiles, product catalogs, or tasksâunderstanding how to work with lists.To render a
4 min read
React FormsIn React, forms are used to take input from users, like text, numbers, or selections. They work just like HTML forms but are often controlled by React state so you can easily track and update the input values.Example:JavaScriptimport React, { useState } from 'react'; function MyForm() { const [name,
4 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. When rendering a list, you need to assign a unique key prop to each element in th
4 min read
Components in React
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects