The Wayback Machine - https://web.archive.org/web/20241001171535/https://www.geeksforgeeks.org/navigate-between-pages-in-nextjs/
Open In App

Navigate Between Pages in NextJS

Last Updated : 25 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Navigating between pages in Next.js is smooth and optimized for performance, with the help of its built-in routing capabilities. The framework utilizes client-side navigation and dynamic routing to ensure fast, smooth transitions and an enhanced user experience.

Prerequisites:

Navigate Between Pages in NextJS

In Next.js, navigation is primarily handled through the <Link> component from next/link, which enables client-side routing. This avoids full page reloads and speeds up page transitions. For programmatic navigation, the useRouter hook from next/router allows navigation based on user actions or logic.

Approach

To provide the navigation between pages we will:

  • Create the Navbar component for navigating on different pages.
  • Create the pages we want to navigate to.
  • Create pages like home.js for the home page, about.js for the about page, contact.js for the contact page and services.js for the services page.
  • Import the Link component in the navbar component from the next/link.
  • Use the Link component to wrap the elements that should trigger the navigation.
  • We will style the links using Bootstrap to make them visually appealing.

Steps to Create NextJS Application

Step 1: Create a NextJS application using the following command

npx create-next-app my-app

Step 2: Navigate to project directory

cd my-app

Project Structure:

Screenshot-(87)
Folder Structure

The updated dependencies in package.json file will look like:

"dependencies": {
    "bootstrap": "^5.3.3",
    "next": "14.1.3",
    "react": "^18"
}

Example: Implementation to navigate between pages in a Next.js application

JavaScript
// components/Navbar.js

import React from "react";
import Link from "next/link";
import "bootstrap/dist/css/bootstrap.min.css";

const Navbar = () => {
    return (
        <div>
            <nav className="navbar navbar-expand-lg navbar-light 
            bg-success bg-opacity-75 text-light">
                <div className="container">
                    <div className="collapse navbar-collapse"
                     id="navbarNav">
                        <ul className="navbar-nav mr-auto">
                            <li className="nav-item">
                                <Link
                                    href="/"
                                    className="nav-item nav-link text-light"
                                    style={{ fontSize: "30px" }}
                                >
                                    Home
                                </Link>
                            </li>
                            <li className="nav-item">
                                <Link
                                    href="/about"
                                    className="nav-item nav-link text-light"
                                    style={{ fontSize: "30px" }}
                                >
                                    About
                                </Link>
                            </li>
                            <li className="nav-item">
                                <Link
                                    href="/contact"
                                    className="nav-item nav-link text-light"
                                    style={{ fontSize: "30px" }}
                                >
                                    Contact
                                </Link>
                            </li>
                            <li className="nav-item">
                                <Link
                                    href="services"
                                    className="nav-item nav-link text-light"
                                    style={{ fontSize: "30px" }}
                                >
                                    Sevices
                                </Link>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        </div>
    );
};

export default Navbar;
JavaScript
// components/Layout.js

import React from 'react';
import Navbar from "@/Components/Navbar";

const Layout = ({ children }) => {
    return (
        <div>
            <Navbar />
            <main>{children}</main>
        </div>
    );
};

export default Layout;
JavaScript
// page.js

import React from 'react'
import Home from '@/pages/Home';

const page = () => {
    return (
        <>
            <Home />
        </>
    )
}

export default page;
JavaScript
// pages/Home.js

import React from 'react'
import Layout from '@/Components/Layout'

const Home = () => {
    return (
        <Layout >
            <div className="container mt-2">
                <h3>Welcomo to GeeksForGeeks</h3>
                <div>This is <b>Home</b> page</div>
            </div>
        </Layout>
    )
}
export default Home;
JavaScript
// pages/about.js

import Layout from '@/Components/Layout'
import React from 'react'

const About = () => {
    return (
        <Layout >
            <div className="container mt-2">
                This is <b>About</b> page</div>
        </Layout>)
}

export default About
JavaScript
// pages/contact.js

import Layout from '@/Components/Layout'
import React from 'react'

const Contact = () => {
    return (
        <Layout >
            <div className="container mt-2">
                This is <b>Contact</b> page</div>
        </Layout>
    )
}

export default Contact
JavaScript
// pages/services.js

import Layout from '@/Components/Layout'
import React from 'react'

const services = () => {
    return (
        <Layout >
            <div className="container mt-2">
                This is <b>Service</b> page</div>
        </Layout>
    )
}

export default services;

Output:

lnk
Navigate Between Pages in NextJS


Previous Article
Next Article

Similar Reads

How to navigate between web pages using javascript history API ?
In this article, we’ll look at how to use history API to navigate between pages. We use History API to navigate programmatically between web pages. History API provides us with a way to access the browser's session history. It exposes useful methods and properties that let you navigate back and forth through the user's history, and manipulate the c
2 min read
Accelerated Mobile Pages (AMP pages)
As we are seeing the demand for mobile phones is very large as compared to desktops or laptops. According to some sources, India has over 1.2 billion mobile phone users that's why good organizations start focusing on mobile phones first. So a question comes to mind how we can increase performance and user experience on mobiles? Let's discuss about
5 min read
How To Add Navbar To All Pages In NextJS ?
A navbar is a common UI element used to navigate between different sections or pages of a website. Adding a navbar to all pages ensures consistent navigation across the site. This article will explore how we can add a navbar to all pages In NextJS. Output Preview: Prerequisites:NextJSReactJSReact HooksReact RouterApproachTo add navbar to all the pa
3 min read
Difference between Link and Navigate Component in React Router
In this article, we'll delve into the intricacies of two fundamental components within the widely acclaimed React Router Dom Library a Link and Navigate. As the backbone of many react applications, these components play pivotal roles in facilitating seamless navigation and routing. We'll explore their respective functionalities, and use cases and m
4 min read
How to navigate to a parent route from a child route?
In angular, a root component that serves as the parent component of all the components and the rest of the other components can be called a Child Component to the root component. This structure is in a form of a tree where a component that is the parent of a child lies above the child component and this there is no direct link between them but in g
4 min read
How to define where to navigate when using the arrow keys in CSS ?
In this article, we will learn how to define where to navigate when using the arrow keys in CSS. Approach: We can do this task by using nav-up, nav-down, nav-right, and nav-up CSS properties together. These properties are used to navigate through the navigation key from the keyboard. The properties define where to focus when the user is navigating
2 min read
Navigate Component in React Router
The navigate component is among the built-in components shipped in with React router version 6. It is a component similar to the useNavigate hook. Internally it uses useNavigate to redirect the location. The props passed to Navigate are the same as the arguments passed to the function returned by useNavigate. While functional components in React su
4 min read
How do you navigate programmatically in Angular?
Angular is a popular framework for building dynamic web applications, and one of its important features is its routing system. In Angular, we use a Router module, which allows us to navigate between different components easily. While navigation often occurs as a result of certain user actions like clicking on a link, there are also several use case
3 min read
How to programmatically navigate using React Router ?
React Router provides a way to navigate between different parts of an application when certain events occur, such as button clicks or form submissions. Programmatically navigating allows us to change the URL of an application without a full page reload, enabling a smoother user experience. We will discuss the different approaches to navigating usin
3 min read
Angular 17 router.navigate
The router.navigate method in Angular 17 is used to navigate to a specific route programmatically. It allows you to change the browser URL and load the corresponding component without the need for a traditional link or reload. This is particularly useful when you want to navigate based on user interactions or application logic. PrerequisitesAngular
2 min read
How to Navigate Fragment URL in Angular 15?
Fragment navigation is important in Angular applications for creating deep linking and bookmarking functionality within a single-page application (SPA). It allows users to navigate directly to specific sections or components within a page without reloading the entire page, enhancing user experience and facilitating content sharing and navigation. P
3 min read
Backbone.js navigate Router
Backbone.js is a compact library used to organize JavaScript code. MVC/MV* framework is another term for it. If you're not familiar, MVC is just a design approach for user interfaces. Designing the user interface of programs is significantly easier when JavaScript features are used. A few of the building elements that are offered in BackboneJS to a
3 min read
How To Navigate To The Git Root Directory?
Navigating to the Git root directory is a common task for developers working with Git repositories. The git root directory is the top-level directory of a Git repository, containing the .git directory where Git stores all its configuration and history information. Why Navigate to the Git Root Directory?Consistent Paths: Many Git commands and script
2 min read
How to Get Browser to Navigate URL in JavaScript?
As a web developer, you may need to navigate to a specific URL from your JavaScript code. This can be done by accessing the browser's window object and using one of the available methods for changing the current URL. In JavaScript, there are several approaches for navigating to a URL. The most commonly used methods are: Using window.location.hrefTh
4 min read
How to navigate URL in an iframe with JavaScript ?
To navigate the URL in an iframe with JavaScript, we have to set the src attribute or return the value of the src attribute in an iframe element. The src attribute defines the URL of the document that can be shown in an iframe. Syntax:document.getElementById("selector").src = "URL";URL values: Absolute URL: It points to another website (For example
1 min read
How to Navigate on Path by Button Click in React Router ?
Navigation in React JS is done by implementing the routing between components using react-router-dom. To set navigation for components or events like button click, we can use the useHistory Hook provided in the react-router-dom v5. Prerequisites:NPM & Node.jsReact JSReact-Router-DomApproachTo navigate on the path by clicking a button we use the
3 min read
How to Share Data Between Pages in Next.js?
Sharing data between pages in Next.js can be crucial for maintaining state and passing information efficiently. You can achieve this with the help of URL parameters. In this article, we will learn about how to share data between pages in next.js Approach to Share Data Between PagesUse the Link component from Next.js and pass an href prop containing
2 min read
How to enable routing and navigation between component pages in Angular 8 ?
The task is to enable routing between angular components by making their routes when a user clicks the link, it will be navigated to page link corresponding to the required component. Let us know what is routing in Angular Angular 8 routing: The Angular 8 Router helps to navigate between pages that are being triggered by the user's actions. The nav
2 min read
Linking between pages in Next.js
In this article, we are going to see how we can link one page to another in Next.js. Follow the below steps to set up the linking between pages in the Next.js application: To create a new NextJs App run the below command in your terminal: npx create-next-app GFGAfter creating your project folder (i.e. GFG ), move to it by using the following comman
3 min read
Difference between NextJS Link vs useRouter in Navigating
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. One of its features is navigation. Navigation is crucial for providing users with seamless browsing experiences. Next.js provide
3 min read
How To Handle Loading Between Page Changes in NextJS?
To experience smooth transitions between the pages of your Next.js application, you can include a loading indicator that shows the progress of the page being loaded. This can be done by creating a custom spinner component and using it during page transitions. In this article, we will create a custom spinner component and display it between page tra
4 min read
How to make “spoiler” text in github wiki pages?
GitHub Wiki pages support GitHub Flavored Markdown. Read more about GitHub flavored markdown here: Mastering MarkdownGitHub Flavored Markdown Spec However, there is no direct method to add a spoiler text in GitHub Flavored Markdown. But, there's a workaround! Approach: Markdown Supports HTML Blocks in it. So, we can use HTML's <details> and
1 min read
Save Pages as HTML in ElectronJS
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. All Chromium browsers support saving webpages as H
6 min read
Deployment of Angular Application using Github Pages
There are various methods to deploy Angular Application such as Github Pages, Heroku, Firebase, etc. The Github provides the simplest way of all using the Github Pages. Steps to Create and Deploy Sample Angular Application to Github Pages: Install Node.js: a. Windows b. LinuxInstall Angular - CLICreate new project using Angular CLI: ng new gfg-exam
2 min read
Web Pages
A webpage is a digital document that is linked to the World Wide Web and viewable by anyone connected to the internet having a web browser. It can contain any type of information, such as text, color, graphics, animations, videos, sounds, etc. A webpage is a document that is written in the HTML, it can be viewed from the Internet. It can be accesse
2 min read
What is the best way to compare two HTML pages with same data but different markup?
In this article, we will be learning about the best way to compare two HTML pages with the same data but different markup. At first, we need to know how to compare two HTML pages. Now, the most efficient way to check both the pages is to use the hash code of both the page contents and compare it for equality. JavaScript hashCode(): In order to impl
4 min read
How to add quotations and citations to the web pages using HTML ?
In this article, we will see how to add quotations and citations to the web pages using HTML. When we are creating a website or a blog, we face many situations where we want to highlight a certain text. We can use HTML to do the same. HTML provides us with many tags such as <blockquote>,<q>, <abbr> and <cite> to perform diff
3 min read
How to author fast-loading HTML pages ?
Generally, we have seen most of the time when the web page is loading at a slow speed due to spending time downloading the cookies & assets such as images, stylesheets, and scripts, etc, which in turn reduces the overall user experience along with the traffic in the site. This problem can be resolved by optimizing the web page that not only pro
8 min read
How to add a video in WordPress Posts or Pages ?
WordPress is an open-source Content Management System and an interface that is totally based on PHP and MySql which is used to create a dynamic website. Matt Mullenweg developed WordPress and Written in PHP language. WordPress is one of the most popular interfaces that allow users to customize and manage the website from its back-end content manage
3 min read
How to include multiple pages in the single jQuery mobile document ?
In this article, we will learn how to include multiple pages in a single jQuery mobile document. Approach: This can be achieved by creating multiple div's and setting the data-role attribute to page, Now each div will represent one page, and each div needs to have a unique id for proper linking between the pages. The jQuery Mobile page structure is
2 min read