Search code examples
javascriptreactjsnext.jsnavigation

Issue with navigating to a new page in Next.js


I am encountering an issue while attempting to navigate to a different page using the router.push function in Next.js.

Specifically, I am trying to use a variable named ChangePage to route to another page called "example.js" which consists of a single div element.

However, despite implementing the code, the desired navigation does not occur.

Here is the code snippet I am using:

'use client'
import Link from "next/link";
import { useRouter, usePathname } from "next/navigation";
import Image from "next/image";
import kittycoin from "../../public/kittycoin.png";
import kittyswap from "../../public/kittyswap.png";

export default function Home() {
  const router = useRouter();

  const handleButtonClick = () => {
    router.push("/swap");
  };

  return (
    <div className="flex flex-col items-center justify-center">
      <button
        type="button"
        className={`h-14 w-48 px-4 py-2 border border-transparent font-bold text-xl text-center rounded-2xl text-[#f1f1f1] bg-[#320000] hover:bg-[#230100] focus:outline-none focus:ring-2 focus:ring-orange-600 focus:ring-opacity-50 transition ease-in-out duration-200`}
        onClick={handleButtonClick}
      >
        Swap Tokens
      </button>

      <div className="w-[300px]">
        <Image src={kittyswap} alt="Hero Image" width={600} height={600} />
      </div>
    </div>
  );
}

I have already imported the necessary modules and defined the router variable using the useRouter hook. The button component is intended to trigger the navigation using the router.push function with the desired page path. However, when the button is clicked, no navigation occurs.

I would appreciate any guidance or insights on what might be causing this issue and how I can successfully navigate to the "example.js" page using router.push.

Thank you in advance for your assistance.


Solution

  • To have a /swap route, you need to create a swap folder inside app, inside which you add a page.js file, which will contain the content of your current swap.js file (leading to app/swap/page.js).

    That's because while with the initial pages router, a file creates a route, since Next.js v13, and when using the app router, a route is created by a folder and a page.js is used to render that route, as the doc shows it:

    enter image description here

    Here is (see the last question) where the CLI asks you which one of the routers you want to use:

    enter image description here

    Finally, if you are following along a tutorial and want to use the pages router, the easiest way is to create a new project and answer the CLI accordingly:

    npx create-next-app@latest