DEV Community

Cover image for NextJs 14 : Routing
Grenish rai
Grenish rai

Posted on

NextJs 14 : Routing

If you know React Router, grasping routing in Next.js will be straightforward for you.

What is Routing anyways?

Routing in NextJs refers to how the framework maps URLs to specific components in your application. It allows users to navigate between different sections of your app and keeps the URL in sync with the content being displayed.

How does it work?

Let's get started.

Let's create a Next.js project.
npx create-next-app@latest

We'll choose the default options.

NextJs Installation Default Option

Let's now execute the app with npm run dev

NextJs Web Default

Fast forward to creating a routes.
After clearing the css make a folder inside src/app name it anything you want. I'll make Hello for this example.
After creating folder, inside make a new file with name page.tsx or page.jsx

File Structure

Let's create something inside Hello/page.tsx

export default function Hello() {
  return (
    <div className="h-screen flex justify-center items-center">
      <span className="text-4xl">Hello World Page</span>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Hello World Page

and after that lets modify the page for src/page.tsx

export default function Home() {
  return (
    <div className="h-screen flex flex-col justify-center items-center">
      <span className="text-4xl">Home Page</span>
      <button className="p-2 bg-teal-200 mt-2 rounded-xl">
        Redirect to /Hello
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Home Page

We have already created our Router when we made our Hello/page.tsx page. You can view it by entering /Hello in the URL bar, like this: http://localhost:3000/Hello. This will take you to the Hello/page.tsx page or component.

Now for the final touchups we'll make a button that redirects to the component.

Home/page.tsx

import Link from "next/link";

export default function Hello() {
  return (
    <div className="h-screen flex flex-col justify-center items-center">
      <span className="text-4xl">Hello World Page</span>
      <button className="p-2 bg-teal-200 mt-2 rounded-xl">
        <Link href="/">Redirect to /Home</Link>
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
app/page.tsx

import Link from "next/link";

export default function Home() {
  return (
    <div className="h-screen flex flex-col justify-center items-center">
      <span className="text-4xl">Home Page</span>
      <button className="p-2 bg-teal-200 mt-2 rounded-xl">
        <Link href="/Hello">Redirect to /Hello</Link>
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Here's the final output.

Home Page With Redirection Button

Hello Page With Redirection Button

And that's it.
Now go and build your own webapps with Nextjs.
Happy Learning. :)

Top comments (0)