Sling Academy
Home/Next.js/How to programmatically navigate in Next.js

How to programmatically navigate in Next.js

Last updated: May 30, 2023

Next.js is a fast-growing React framework that can help us build high-performance hybrid static and server-side rendering web applications. Many projects have been transitioning from traditional React SPAs to Next.js, including giants like Github, IGN, Hulu, etc.

In this article, we’ll explore how to programmatically navigate in a Next.js application by using the useRouter hook that comes along with the Next.js core. This will be helpful in some scenarios, like changing routes when the user clicks a button, checks a checkbox, chooses an option from a dropdown select menu, after waiting for a countdown timer, etc.

The useRouter hook

If you’re working with server components in the app directory (that comes with Next.js 13 and newer), you must add the use client directive at the top of your component to be able to use hooks, as shown below:

"use client";
import { useRouter } from 'next/navigation';

export default function Home() {
  const router = useRouter();
  console.log(router);
  return <></>;
}

If you’re still using the pages directory as before, the use client directive is not necessary.

The router object returned by the useRouter hook gives us some useful methods for programmatically navigating:

push() method

The push() method adds a new URL to the history stack:

router.push("/some-destination");

replace() method

This method is similar to the push() method but will NOT add a new URL into the history stack. That means you cannot go back to the previous route by hitting the back button of your browser.

router.replace("/some-target");

back() and forward() method

You can call the back() or the forward() method to go to the previous or the next route, respectively. These methods don’t require any arguments (because their names already tell where to go).

The Complete Example

This example demonstrates how to navigate in Next.js by clicking a button or checking a checkbox. We will use the latest version of Next.js and its app directory.

Preview

Our sample app has 2 only pages: Home and Feedback. There are no links, but the user can press one of the two buttons or check the checkbox to move from the Home page to the Feedback page. Here’s how it works in action:

The Steps

1. To make sure we have the same starting point, please create a new project:

npx create-next-app example

Please select TypeScript when Next.js asks you.

When the project initialization is complete, create a new folder named feedback in the app directory of your project. After that, add a new file calledfeedback.tsx inside the feedback folder.

Here’s the file structure in the app directory:

.
├── feedback
│   └── page.tsx
├── layout.tsx
└── page.tsx

2.. Add the following code to the file:

// app/feedback/page.tsx

const FeedBack = () => {
  return (
    <div style={{ padding: 50 }}>
      <h1>Feedback Page</h1>
    </div>
  );
};

export default FeedBack;

3. And here’s the code in the app/page.tsx:

import { useRouter } from 'next/router';

export default function Home() {
  const router = useRouter();
  return (
    <div style={{ padding: 50 }}>
      <h1>Home Page</h1>
      <h2>push()</h2>
      <p>
        <button onClick={() => router.push('/feedback')}>
          Go to the feedback page
        </button>
      </p>
      <p>
        <input
          type="checkbox"
          onChange={() => router.push('/feedback')}
        ></input> Check me to go to the feedback page
      </p>
      <br />

      <h2>replace()</h2>
      <div>
        <button onClick={() => router.replace('/feedback')}>
          Go to the feedback page and not go back
        </button>
      </div>
    </div>
  );
}

4. Replace the unwanted code (if any) in your app/layout.tsx file with the code below:

// app/layout.tsx (this is the root layout)

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang='en'>
      <body suppressHydrationWarning={true}>{children}</body>
    </html>
  );
}

5. Get your app up and running:

npm run dev

Then go to http://localhost:3000 to see the result.

Next Article: Next.js: Parsing Query String Parameters

Previous Article: How to Change the Base Path in Next.js (Subdirectory Path)

Series: Next.js Navigation and Routing

Next.js

Related Articles

You May Also Like

  • Solving Next.js Image Component Error with CSS Classes
  • How to Use MUI (Material UI) in Next.js 14
  • Fixing Data Update Issues in Next.js Production
  • Fixing Next.js Undefined ENV Variables in Production Build
  • Solving Next.js SyntaxError: Unexpected token ‘export’
  • Next.js Error: Found Page Without a React Component as Default Export – How to Fix
  • Fixing Next.js Error: Blank Page on Production Build
  • Fixing Next.js Error when Importing SVGs: A Step-by-Step Guide
  • Next.js Issue: useEffect Hook Running Twice in Client
  • Fixing ‘self’ is not defined error in Next.js when importing client-side libraries
  • How to Dockerize a Next.js App for Production
  • How to set up Next.js with Docker Composer and Nginx
  • Solving Next.js CORS Issues: A Comprehensive Guide
  • Fixing Next.js Hydration Mismatch Error in Simple Ways
  • Next.js Error: Cannot use import statement outside a module
  • Next.js: How to Access Files in the Public Folder
  • Fixing Next.js Import CSS Error: A Simple Guide
  • Fixing LocalStorage Not Defined Error in Next.js
  • Fixing Next.js Error: No HTTP Methods Exported