Skip to main content

Learning Objectives

By the end of this section, you will be able to:
  • Set up a Next.js 14 project with proper configuration for enterprise applications
  • Analyze the VSL Service Center codebase structure and dependencies
  • Create a comprehensive migration strategy document
  • Configure development environment and tools for the migration project
  • Identify migration priorities and potential challenges
Duration: 3-4 hours

Overview

Next.js App Router provides powerful layout features for creating consistent UI patterns. Understanding layouts is crucial for building maintainable applications.

What are Layouts?

Layouts are shared UI that persists across route changes and maintains state during navigation.

Key Characteristics

Layout Characteristics

  • Shared UI across multiple pages
  • Maintains state during navigation
  • Renders once and stays mounted
  • Perfect for navigation, headers, footers

Layout Benefits

  • Consistent user experience
  • Performance optimization
  • State preservation
  • Reduced re-rendering

Root Layout

The root layout wraps all pages and is required in every Next.js app.
// app/layout.tsx
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "My App",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en" className={inter.className}>
      <body>
        <header>
          <nav>
            <a href="/">Home</a>
            <a href="/about">About</a>
            <a href="/contact">Contact</a>
          </nav>
        </header>
        <main>{children}</main>
        <footer>
          <p>&copy; 2024 My App. All rights reserved.</p>
        </footer>
      </body>
    </html>
  );
}

Nested Layouts

Layouts can be nested to create hierarchical UI structures.
// app/dashboard/layout.tsx
import Sidebar from "@/components/Sidebar";

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <div className="dashboard-layout">
      <Sidebar />
      <div className="dashboard-content">{children}</div>
    </div>
  );
}

Layout Hierarchy

app/
├── layout.tsx              # Root layout (wraps everything)
├── dashboard/
│   ├── layout.tsx          # Dashboard layout (wraps dashboard pages)
│   ├── page.tsx            # /dashboard
│   └── settings/
│       ├── layout.tsx      # Settings layout (wraps settings pages)
│       └── page.tsx        # /dashboard/settings

Basic Layout Patterns

Simple Layout with Navigation

// app/layout.tsx
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <div className="min-h-screen flex flex-col">
          <header className="bg-white shadow-sm">
            <nav className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
              <div className="flex justify-between items-center">
                <div className="flex space-x-8">
                  <a href="/" className="text-gray-900">
                    Home
                  </a>
                  <a href="/about" className="text-gray-900">
                    About
                  </a>
                  <a href="/contact" className="text-gray-900">
                    Contact
                  </a>
                </div>
              </div>
            </nav>
          </header>

          <main className="flex-1">{children}</main>

          <footer className="bg-gray-800 text-white">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
              <p>&copy; 2024 My App. All rights reserved.</p>
            </div>
          </footer>
        </div>
      </body>
    </html>
  );
}

Dashboard Layout

// app/dashboard/layout.tsx
import Sidebar from "@/components/Sidebar";
import Header from "@/components/Header";

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <div className="dashboard-layout">
      <Sidebar />
      <div className="dashboard-main">
        <Header />
        <div className="dashboard-content">{children}</div>
      </div>
    </div>
  );
}

Layout with Metadata

// app/blog/layout.tsx
import { Metadata } from "next";

export const metadata: Metadata = {
  title: "Blog - My App",
  description: "Read our latest blog posts",
};

export default function BlogLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <div className="blog-layout">
      <aside className="blog-sidebar">
        <h2>Categories</h2>
        {/* Category links */}
      </aside>
      <main className="blog-main">{children}</main>
    </div>
  );
}

Best Practices for Module 1

Layout Design

  1. Keep Layouts Simple: Focus on shared UI elements and avoid complex logic
  2. Use Nested Layouts: Create hierarchical layouts for better organization
  3. Optimize Performance: Minimize re-renders and use proper state management
  4. Handle Loading States: Provide appropriate loading states
Key Takeaway: Layouts are powerful tools for creating consistent UI patterns. Use them for shared UI that should persist across routes, like navigation, headers, and footers.

Part 1: Strategic Analysis & Planning

VSL Service Center Codebase Analysis

Let’s analyze the existing VSL Service Center structure to understand what we’re working with:

Current Structure

  • Create React App with React Router - Component-based architecture - CSS modules for styling - Axios for API calls - Local storage for state management

Key Components

  • LandingPage: Main dashboard - Navbar: Navigation with dynamic menus - Master components: CRUD operations - Transaction components: Business logic
  • Report components: Data visualization

Component Categories Analysis

  • Components: Card.jsx, Badge.jsx, Stat.jsx, Table.jsx
  • Migration Strategy: Direct conversion to Next.js components
  • Priority: High (foundation components)
  • Estimated Time: 1-2 hours per component
  • Components: Navbar.js, Footer.js, SideBar.js
  • Migration Strategy: Convert to Next.js layouts and navigation
  • Priority: High (core navigation)
  • Estimated Time: 3-4 hours per component
  • Components: MaterialInward.js, ProductionEntry.js, Dashboard.js
  • Migration Strategy: Separate server/client logic, implement server actions
  • Priority: Medium (can be done after foundation)
  • Estimated Time: 4-6 hours per component
  • Components: BarcodeScanner.js, WebcamCapture.js, WhatsApp integration
  • Migration Strategy: Client components with proper hydration
  • Priority: Low (can be done last)
  • Estimated Time: 6-8 hours per component

Migration Strategy Development

Phase 1: Foundation Setup (Week 1)

1

Project Infrastructure

  • Set up Next.js project with proper configuration
  • Configure TypeScript and ESLint
  • Set up Tailwind CSS and component library
  • Create basic project structure
2

Core Components Migration

  • Migrate UI components (Card, Badge, Table)
  • Create layout components (Navbar, Footer)
  • Set up routing structure
  • Implement basic authentication flow
3

Data Layer Setup

  • Set up API routes structure
  • Configure database connections
  • Implement basic CRUD operations
  • Set up error handling

Phase 2: Core Features (Week 2)

1

Master Data Management

  • Migrate customer, supplier, material management
  • Implement server actions for CRUD operations
  • Add form validation and error handling
  • Test data persistence
2

Authentication & Authorization

  • Implement JWT-based authentication
  • Set up role-based access control
  • Migrate user management features
  • Test security implementation
3

Basic Transactions

  • Migrate simple transaction components
  • Implement data fetching patterns
  • Add loading states and error handling
  • Test business logic

Part 2: Hands-On Implementation

Exercise 1: Create Migration Strategy Document

Create a comprehensive migration strategy document with the following sections:
# VSL Service Center Migration Strategy

## 1. Project Overview

- Current technology stack analysis
- Target technology stack
- Migration objectives and success criteria

## 2. Component Analysis

- Component inventory and categorization
- Migration complexity assessment
- Dependencies and integration points

## 3. Migration Phases

- Phase 1: Foundation (Week 1)
- Phase 2: Core Features (Week 2)
- Phase 3: Advanced Features (Week 3+)

## 4. Risk Assessment

- Technical risks and mitigation strategies
- Timeline risks and contingency plans
- Resource requirements and availability

## 5. Testing Strategy

- Unit testing approach
- Integration testing plan
- User acceptance testing criteria

Exercise 2: Set Up Next.js Project

  1. Create the Next.js project:
    npx create-next-app@latest vsl-service-center-nextjs \
      --typescript \
      --tailwind \
      --eslint \
      --app \
      --src-dir \
      --import-alias "@/*"
    
    cd vsl-service-center-nextjs
    
  2. Install required dependencies:
    # UI and styling dependencies
    npm install @mui/material @emotion/react @emotion/styled
    npm install @mui/icons-material @mui/x-data-grid
    npm install ag-grid-community ag-grid-react
    
    # Data handling and utilities
    npm install axios moment
    npm install file-saver jspdf jspdf-autotable
    npm install html-to-image xlsx
    
    # Barcode and scanning
    npm install bwip-js react-barcode-reader react-barcode-scanner
    npm install react-qr-barcode-scanner react-qr-code
    
    # Charts and visualization
    npm install chart.js react-chartjs-2
    
    # Date handling
    npm install react-datepicker
    
    # Notifications and UI feedback
    npm install react-toastify react-to-print
    
    # Development dependencies
    npm install -D @types/file-saver
    
  3. Set up project structure:
    mkdir -p src/components/{ui,forms,charts,common}
    mkdir -p src/lib src/types
    mkdir -p src/app/{\(auth\),dashboard,master/{customers,suppliers,materials},transactions/{inward,outward},reports,visitor,yms}
    

Exercise 3: Configure Project Structure

Create the initial project structure that mirrors the VSL Service Center organization:
src/
├── app/
│   ├── (auth)/
│   │   ├── login/
│   │   │   └── page.tsx
│   │   └── layout.tsx
│   ├── dashboard/
│   │   └── page.tsx
│   ├── master/
│   │   ├── customers/
│   │   ├── suppliers/
│   │   ├── materials/
│   │   └── layout.tsx
│   ├── transactions/
│   │   ├── inward/
│   │   ├── outward/
│   │   └── layout.tsx
│   ├── reports/
│   │   └── page.tsx
│   ├── visitor/
│   │   └── page.tsx
│   ├── yms/
│   │   └── page.tsx
│   ├── globals.css
│   ├── layout.tsx
│   └── page.tsx
├── components/
│   ├── ui/
│   ├── forms/
│   ├── charts/
│   └── common/
├── lib/
│   ├── utils.ts
│   ├── api.ts
│   └── database.ts
└── types/
    └── index.ts

Exercise 4: Analyze VSL Components

  1. Examine the VSL Service Center components:
    • Review src/Component/ui/Card.jsx
    • Analyze src/Component/Navbar.js
    • Study src/Component/LandingPage.js
  2. Create component analysis document:
    • List all components and their purposes
    • Identify server vs client component candidates
    • Note dependencies and integration points
    • Estimate migration complexity
  3. Plan the first 3 components to migrate:
    • Choose 3 components from the UI folder
    • Document their current implementation
    • Plan the Next.js migration approach
    • Estimate time and effort required

Part 3: Reflection & Extension

Assessment Criteria

Your migration strategy will be evaluated based on:

Technical Analysis

  • Accurate assessment of current architecture - Proper identification of migration challenges - Realistic timeline and effort estimates - Appropriate technology choices

Strategic Planning

  • Clear migration phases and priorities - Risk identification and mitigation
  • Resource planning and allocation - Success criteria and milestones

Common Challenges & Solutions

Challenge: Managing complex dependencies from the original React app Solution: Use package.json analysis tools and create a dependency migration plan
Challenge: Converting local storage and component state to Next.js patterns Solution: Plan server state vs client state separation early
Challenge: Converting React Router to Next.js App Router Solution: Create a routing mapping document and plan URL structure
Challenge: Converting CSS modules to Tailwind CSS Solution: Create a design system and component style guide

Extension Activities

  1. Research Next.js 14 Features:
    • Investigate new App Router capabilities
    • Study server actions and form handling
    • Explore performance optimization techniques
  2. Plan Advanced Migration Strategies:
    • Consider incremental migration approaches
    • Plan for zero-downtime deployment
    • Design rollback strategies
  3. Create Migration Checklist:
    • Develop a comprehensive checklist for each component type
    • Include testing and validation steps
    • Plan for code review and quality assurance

Next Steps

After completing this lesson, you’ll be ready to move on to Lesson 1.3: Component Migration & Routing, where you’ll:
  • Migrate your first React components to Next.js
  • Implement the new routing structure
  • Set up layouts and templates
  • Test the migrated components
Key Takeaway: A well-planned migration strategy is crucial for success. Take time to analyze the existing codebase thoroughly and create a realistic plan that accounts for complexity, dependencies, and business requirements.