How to Change URL Without Page Refresh in Next.js?
Last Updated :
20 May, 2024
In web development, the ability to change URLs dynamically without triggering a full page refresh is essential for creating smooth, seamless user experiences. Next.js, a popular React framework, offers built-in features to achieve this efficiently through its client-side routing capabilities. In this article, we'll explore various techniques and approaches to change URLs without page refresh in Next.js applications.
Prerequisites:
Understanding Client-Side Routing in Next.js
Next.js uses client-side routing to handle navigation between pages without reloading the entire application. It uses the HTML5 History API to manipulate browser history and update the URL in the address bar dynamically.
Using Link Component for Navigation
Next.js provides the <Link> component to enable client-side navigation between pages. You can import the <Link>
component from the 'next/link' module and use it to wrap anchor tags (<a>
), specifying the href
attribute to indicate the target URL.
Steps to Setup NextJS Application
Step 1: Create a NextJS application using the following command
npx create-next-app my-app
Step 2: Navigate to the Project directory
cd my-app
Step 3:Â Install the necessary packages/libraries in your project using the following commands.
npm i bootstrap
Project Structure:
.png)
The updated dependencies in package.json file will look like:
"dependencies": {
"bootstrap": "^5.3.3",
"next": "14.1.3",
"react": "^18"
}
Approach
- Create Navbar component to contain links to different pages.
- Design a Layout component to keep Navbar at each page.
- Create different pages like Home, About, Contact, and Services.
- Import the Link component in the navbar component from the next/link.
- Use the Link component to change the URl without page refresh.
- Add basic styling to links using Bootstrap to make them visually appealing.
Example: In example below, we have created a Navbar containing links to different pages, demonstrating how to change the URL without refreshing the page in Next.js.
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-primary
g-opacity-75 text-light">
<div className="container">
<div 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
// pages/index.js
import React from 'react'
import Layout from '@/Components/Layout';
const Home = () => {
return (
<Layout >
<div className="container mt-2">
<h2 className='text-success'>Welcomo to GeeksForGeeks</h2>
<h3>Home page</h3>
</div>
</Layout>
)
}
export default Home;
JavaScript
//About.js
import Layout from '@/Components/Layout'
import React from 'react'
const About = () => {
return (
<Layout >
<div className="container mt-2">
<h3>About page</h3>
</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">
<h3>Contact page</h3>
</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">
<h3>Services page</h3>
</div>
</Layout>
)
}
export default services;
Step to Run Application:Â Run the application using the following command from the root directory of the project
npm run dev
Output:Â Your project will be shown in the URL http://localhost:3000/
Similar Reads
How to change port in Next.js App
Next.js provides the flexibility to change the default port of the development server using command-line options such as -p <port_number> or by updating the "scripts" section in the package.json file, offering developers multiple ways to customize the port configuration based on their requirem
3 min read
How to Handle a Post Request in Next.js?
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. In this article, we will learn about How to handle a post request in NextJS. A
2 min read
How to Get URL pathname in Next.js?
Next.js is a powerful React framework that simplifies the process of building server-rendered and statically generated web applications. One common requirement in web development is to get the URL pathname, which can be useful for various purposes such as conditional rendering, routing, and analytic
3 min read
How to Refresh a Page using jQuery?
Refreshing a page using jQuery allows you to programmatically reload the current webpage, ensuring updated content or resetting the page's state. It can be done using location.reload() method.Table of ContentUsing location.reload() MethodUsing history.go(0)Using location.replace() with Current PageR
3 min read
How to Get Query Parameters from URL in Next.js?
In Next.js, getting query parameters from the URL involves extracting key-value pairs from the URL string to access specific data or parameters associated with a web page or application, aiding in dynamic content generation and customization.To get query parameters from the URL in next.js we have mu
5 min read
How to use CORS in Next.js to Handle Cross-origin Requests ?
NextJS simplifies server-side logic with its API routes, reducing the need for separate server maintenance. CORS, usually configured on the server, can be handled within NextJS API routes directly. These routes, integrated into the application codebase, allow control over request origins. By impleme
7 min read
How To Get URL And URL Parts In JavaScript?
In web development, working with URLs is a common task. Whether we need to extract parts of a URL or manipulate the URL for navigation, JavaScript provides multiple approaches to access and modify URL parts. we will explore different approaches to retrieve the full URL and its various components.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.jsApproach to Share Data Between PagesUse the Link compon
2 min read
How To Get Current Route In Next.js?
Next.js is a popular React framework that makes it easy to build server-side rendered and static web applications. One common task in web development is determining the current route or URL of the page. In Next.js, this can be done using the built-in useRouter hook. This article will guide you throu
3 min read
How to Get The Current URL Domain in Next.js ?
In Next.js, we can get current url domain with the help of built-in methods like window and document location. In this article, we'll explore different approaches and best practices for obtaining the current URL domain in Next.js applications.The approaches to get the URL of the current domain in ne
3 min read