πŸš€ Understanding Nested Routes and Layout and Conditional Layout in Next.js

In Next.js, nested routes are created by organizing files inside folders under the app/ directory (App Router).

πŸ“Œ Example of Nested Routes

Create a folder Anyname/ inside app/.Create an other folder otherName/ inside Then add files like :

  • /User/shoaib/page.jsx
  • /User/zohaib/page.jsx
  • /User/arslan/page.jsx

πŸ–Œ Shared Layouts for Nested Routes

Create a layout.jsx file inside the nested-routing/ folder. It will wrap all child pages.

You can also add conditional layout logic. For example, here we’re hiding the layout section on the /arslan page.

Below is the layout code:

'use client'
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import React from 'react';

const Layout = ({ children }) => {
  const pathname = usePathname();

  return (
    <div>
      {children}

{/* Conditional Layout Rendering: hide on /nested-routing/arslan */}
      {pathname === '/nested-routing/arslan' ? null : (
        <div className="m-6 text-center">
          <p className="text-gray-600 mt-2">This is rendered from the layout component</p>
          <Link href="/nested-routing">
            <span className="bg-red-700 hover:bg-red-900 text-white px-4 py-2 rounded-lg inline-block shadow-md transition">
              πŸ”™ Back to Nested Routing
            </span>
          </Link>
        </div>
      )}
    </div>
  );
};

export default Layout;

This is rendered from the layout component

πŸ”™ Back to Nested Routing