Loading...

How to programmatically navigate to a page in Next.js?

question nextjs react
Ram Patra Published on July 18, 2024
Tested on Next.js 14

In Next.js, you can programmatically navigate to different pages using the useRouter hook from the next/navigation module. This hook provides a convenient way to navigate between pages within your Next.js application. Below is an example demonstrating how to use the useRouter hook to programmatically navigate to another page.

Step-by-Step Example

  1. Install Next.js (if you haven’t already):
     npx create-next-app@latest my-next-app
     cd my-next-app
     npm run dev
    
  2. Create a new page: Let’s create a new page to navigate to. Create a file named page.jsx in the about directory.

     // app/about/page.jsx
     export default function About() {
         return (
             <div>
                 <h1>About Page</h1>
                 <p>This is the about page.</p>
             </div>
         );
     }
    
  3. Set up navigation in another component: Use the useRouter hook to navigate to the “About” page when a button is clicked. Modify the index.jsx file in the app directory.

     // app/index.jsx
     import { useRouter } from 'next/navigation';
     import React from 'react';
    
     export default function Home() {
         const router = useRouter();
    
         const navigateToAbout = () => {
             router.push('/about');
         };
    
         return (
             <div>
                 <h1>Home Page</h1>
                 <button onClick={navigateToAbout}>Go to About Page</button>
             </div>
         );
     }
    
  4. Run the Next.js development server:
     npm run dev
    

Now, when you open your browser and navigate to http://localhost:3000, you should see the Home Page with a button labeled “Go to About Page.” When you click the button, it will programmatically navigate to the About Page.

Detailed Explanation

  • useRouter Hook:
    • The useRouter hook from next/navigation gives you access to the router object, which includes methods for navigation.
      import { useRouter } from 'next/navigation';
    
  • router.push:
    • router.push('/about') is used to navigate to the /about page. This is similar to navigating using a link but done programmatically.
      const navigateToAbout = () => {
          router.push('/about');
      };
    
  • Button Click Handler:
    • The navigateToAbout function is called when the button is clicked, triggering the navigation.
      <button onClick={navigateToAbout}>Go to About Page</button>
    

This approach can be extended to navigate to different pages, pass query parameters, or even handle more complex routing logic as required in your Next.js application.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

KeyScreen

Show keypresses on your screen.

ToDoBar

Your to-dos on your menu bar.

SimpleFill

Fill forms using your right-click menu.

IconSim

Preview your Mac app icons.

Ram Patra Published on July 18, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question nextjs vercel March 1, 2025 Three ways to disable Image Optimization in Vercel

If you’re using the free tier of Vercel, like I do for some of my small side projects, you will get the 402 Payment Required error eventually when loading images. This is because you have hit the Image Optimization limit of the free plan. The solution to this is to disable Vercel’s Image Optimization, or to host the images elsewhere, or to upgrade to their Pro plan.

question nextjs cloudflare March 19, 2025 How to run a website built with Next.js 15 on Cloudflare Pages?

If you simply connect a website’s code on GitHub with Cloudflare Pages that’s built using Next.js 15+, it may not build successfully out of the box. If this is the case with you, make sure to do the following.

question nextjs front-end July 21, 2024 How to fix Next.js generating Open Graph images with localhost in the url?

This happens when you have not set the metadata properly. Just make sure you have set the metadataBase property like below:export const metadata = { metadataBase: new URL('https://rampatra.com'), // other configs}Learn more from the official docs.

Like my work?

Please, feel free to reach out. I would be more than happy to chat.