Wednesday, November 20, 2024
Google search engine
HomeLanguagesNext.js next/link

Next.js next/link

Next.js is a popular open-source framework built on top of React, designed to help developers build server-rendered React applications. One of its powerful features is the ability to create client-side transitions between pages without triggering a full page reload, thanks to the built-in next/link component. In this article, we will learn how to use next/link by building a small Next.js application.

What is next/link?

The next/link is a React 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
import Link from 'next/link';

// Link component
<Link href="/page">New Page</Link>

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.

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/link

NextJs next/link

Basic 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:

Filename: index.js

Javascript




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. 

Filename: about.js

Javascript




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/link

NextJs next/link

In 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. 

Filename: blog/[slug].js:

Javascript




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>
    );
}


Modify index.js to include a list of blog posts with links to the individual post pages:

Javascript




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/link

NextJs next/link

In 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.

In conclusion, next/link is a powerful tool that simplifies navigation in Next.js applications, enabling fast and responsive client-side rendering. Its straightforward syntax and ease of use make it a popular choice among developers for creating links between pages and dynamic routing.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments