NEXTJS Routes or Routing

Routing Rules

  • All routes must be placed iside the app folder.
  • Every folder corresponds to a path segment in the browser URL.
 app
   home
     page.jsx
  • Every file that represents a route must be named page.jsx

Routes

export default function Home(){
  return <h1> This is Home </h1>
}

home
  page.jsx

Route Groups = ( )

(needed-pages)
   home
     page.jsx
   about
     page.jsx
   contact
     page.jsx

Dynamic Routes = [ ]

blog
   page.jsx
   [id]
     page.jsx

How to access dynamic params value?

export default function ProductDetails({ params }){
    return <h1> Details of Product {params.idd} </h1>
 }

/products/:

Not Found Page

app
  not-found.js or not-found.jsx
export default function Notfound(){
  return(
    <div>
      <h2>Page Not Found</h2>
      <p>Could Not find requested page</p>
    </div>
  )
}

Private Folders = _

A feature provided by Next.js to effectively organise your project.

Note: The folder and all its subfolders are excluded from routing.

app
  _private
     page.jsx
export default function PrivateRoute(){
    return <h1> You can't view this in the browser</h1>
 }

Note: To have underscore in URL segments prefix the folder name with ‘%5F’ ; which is the URL-encoded

import { Link } from ‘react-router-dom’

<Link to=”/”><button className={styles.button}>Go to Home</button></Link>

import Link from 'next/link';
<Link href="/about">Go to About Page</Link>

For ex: on button click i.e. function HandleSubmit()

[Button Click Handler]

It’s a client side because user will click button, so put ‘use client’

Or you will get this error:

import { useRouter } from 'next/navigation';
  const router = useRouter();
    router.push('/about');

import {useNavigate} from “react-router-dom”

    const navigate= useNavigate()

        navigate(‘/checkout’)

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

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

  const handleNavigation = () => {
    router.push('/about'); // Navigates to the about page
  };
  
  return (
    <div>
      <h1>Welcome to the Home Page</h1>
      <button onClick={handleNavigation}>Go to About Page</button>
    </div>
  );
}

/app/product/[id]/page.js
import { useRouter } from 'next/navigation';

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

const goToProduct = (id) => {
    router.push(/product/${id});
};

  return (
    <div>
      <button onClick={() => goToProduct(123)}>View Product 123</button>
    </div>
  );
}