Skip to main content

Tutorial NextJS - Day 2

Hari 2 – Navigasi, Layout, & Dynamic Routing Setelah berhasil melakukan instalasi dan membuat halaman pertama di Hari 1 , pada Hari 2 ini kita akan membuat website menjadi lebih hidup. Kita akan belajar cara membuat menu navigasi agar bisa pindah-pindah halaman, membuat tampilan menu yang konsisten (Layout), dan membuat halaman artikel yang pintar (Dynamic Routing). Tutorial ini tetap menggunakan Windows + VS Code dan melanjutan project nextjs-basic dari hari sebelumnya. 1. Navigasi Antar Halaman ( <Link> ) Di HTML biasa, kita menggunakan tag <a> untuk berpindah halaman. Namun, di Next.js kita menggunakan komponen khusus bernama <Link> . Kenapa harus pakai <Link> ? Jika pakai <a> , layar akan berkedip (loading ulang) setiap pindah halaman. Dengan <Link> , perpindahan halaman terjadi instan tanpa refresh. 1.1 Edit Halaman Home Kita akan menambahkan tombol untuk pergi ke halaman About. Buka file src/app/page.tsx , lalu ganti isinya dengan kod...

Tutorial NextJS - Day 2

Hari 2 – Navigasi, Layout, & Dynamic Routing

Setelah berhasil melakukan instalasi dan membuat halaman pertama di Hari 1, pada Hari 2 ini kita akan membuat website menjadi lebih hidup. Kita akan belajar cara membuat menu navigasi agar bisa pindah-pindah halaman, membuat tampilan menu yang konsisten (Layout), dan membuat halaman artikel yang pintar (Dynamic Routing).

Tutorial ini tetap menggunakan Windows + VS Code dan melanjutan project nextjs-basic dari hari sebelumnya.

1. Navigasi Antar Halaman (<Link>)

Di HTML biasa, kita menggunakan tag <a> untuk berpindah halaman. Namun, di Next.js kita menggunakan komponen khusus bernama <Link>.

Kenapa harus pakai <Link>? Jika pakai <a>, layar akan berkedip (loading ulang) setiap pindah halaman. Dengan <Link>, perpindahan halaman terjadi instan tanpa refresh.

1.1 Edit Halaman Home

Kita akan menambahkan tombol untuk pergi ke halaman About. Buka file src/app/page.tsx, lalu ganti isinya dengan kode ini:

TypeScript
import Link from 'next/link'; // 1. Wajib import ini

export default function Home() {
  return (
    <div className="p-10">
      <h1 className="text-2xl font-bold">Hello Next.js</h1>
      <p className="mb-5">Ini adalah hari kedua belajar Next.js</p>
      
      {/* 2. Gunakan Link pengganti tag <a> */}
      <Link href="/about" className="text-blue-500 underline">
        Pindah ke Halaman About →
      </Link>
    </div>
  );
}

1.2 Edit Halaman About

Sekarang kita tambahkan tombol untuk kembali ke Home. Buka file src/app/about/page.tsx, ganti isinya:

TypeScript
import Link from 'next/link';

export default function About() {
  return (
    <div className="p-10">
      <h1 className="text-2xl font-bold">Halaman About</h1>
      <p className="mb-5">Ini adalah halaman tentang saya.</p>
      
      <Link href="/" className="text-blue-500 underline">
        ← Kembali ke Home
      </Link>
    </div>
  );
}

Coba sekarang: Jalankan npm run dev, buka browser, dan coba klik link tersebut. Perpindahannya sangat cepat, bukan?


2. Layouts (Membuat Navbar Otomatis)

Capek kan kalau harus membuat tombol menu di setiap halaman? Di Next.js, kita punya file spesial bernama layout.tsx. Apapun yang kita tulis di sini akan muncul di semua halaman.

Kita akan membuat Navbar (Menu Atas) sederhana.

2.1 Edit Global Layout

Buka file src/app/layout.tsx. Hapus semua isinya, dan ganti dengan kode berikut agar lebih rapi:

TypeScript
import Link from "next/link";
import "./globals.css";

export const metadata = {
  title: "Belajar Next.js",
  description: "Tutorial Next.js Dasar",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body className="bg-white text-black">
        {/* BAGIAN 1: NAVBAR (Akan muncul di semua halaman) */}
        <nav className="p-5 bg-gray-800 text-white flex gap-5">
          <Link href="/" className="font-bold hover:text-gray-300">Home</Link>
          <Link href="/about" className="font-bold hover:text-gray-300">About</Link>
          <Link href="/blog" className="font-bold hover:text-gray-300">Blog</Link>
        </nav>

        {/* BAGIAN 2: KONTEN (Berubah sesuai halaman yang dibuka) */}
        <main>
          {children}
        </main>
      </body>
    </html>
  );
}

Sekarang, coba buka halaman Home atau About. Menu hitam di atas akan selalu ada!


3. Persiapan Halaman Blog

Di menu tadi kita menambahkan link ke Blog, tapi halamannya belum ada. Mari kita buat daftar artikelnya dulu.

3.1 Buat Folder dan File Blog

  1. Buat folder baru di dalam src/app/ dengan nama blog.

  2. Di dalam folder blog, buat file baru bernama page.tsx.

Isi file src/app/blog/page.tsx dengan kode ini:

TypeScript
import Link from "next/link";

export default function BlogPage() {
  return (
    <div className="p-10">
      <h1 className="text-2xl font-bold mb-5">Daftar Artikel</h1>
      
      {/* Daftar Link Manual */}
      <ul className="list-disc pl-5 space-y-3">
        <li>
          <Link href="/blog/belajar-nextjs" className="text-blue-600 hover:underline">
            Artikel 1: Cara Belajar Next.js
          </Link>
        </li>
        <li>
          <Link href="/blog/tutorial-react" className="text-blue-600 hover:underline">
            Artikel 2: Tutorial React Dasar
          </Link>
        </li>
        <li>
          <Link href="/blog/tips-coding" className="text-blue-600 hover:underline">
            Artikel 3: Tips Coding Pemula
          </Link>
        </li>
      </ul>
    </div>
  );
}

4. Dynamic Routing (Satu Halaman untuk Semua Artikel)

Jika kamu punya 100 artikel, tidak mungkin kamu membuat 100 file satu per satu. Solusinya adalah Dynamic Routing.

Kita akan membuat "Halaman Cetakan". Apapun judul artikel yang diklik, akan ditangani oleh satu file ini.

4.1 Buat Folder Dynamic

  1. Di dalam folder src/app/blog/, buat folder baru.

  2. Beri nama foldernya: [slug] (Pastikan pakai kurung siku. slug artinya penanda judul di URL).

4.2 Buat File Halaman Dynamic

Di dalam folder [slug] tadi, buat file page.tsx. Strukturnya jadi: src/app/blog/[slug]/page.tsx.

Isi dengan kode berikut:

TypeScript
// Ini adalah halaman "cetakan"
// params akan menangkap judul yang ada di URL
export default async function DetailArtikel({ params }: { params: { slug: string } }) {
  
  // Kita ambil slug (judul) dari URL
  const { slug } = await params;

  return (
    <div className="p-10">
      <h1 className="text-3xl font-bold text-blue-800">Judul Post: {slug}</h1>
      <p className="mt-5 text-gray-600">
        Halaman ini dibuat otomatis oleh Next.js! <br/>
        Kamu sedang membaca artikel dengan ID: <strong>{slug}</strong>
      </p>

      <div className="mt-10">
        <a href="/blog" className="text-sm text-gray-500">← Kembali ke Daftar Blog</a>
      </div>
    </div>
  );
}

4.3 Uji Coba (Magic Time!)

  1. Buka browser, klik menu Blog.

  2. Klik "Artikel 1: Cara Belajar Next.js".

    • Lihat URL-nya: /blog/belajar-nextjs

    • Lihat Judul di halaman: Judul Post: belajar-nextjs

  3. Coba ganti URL di browser sembarangan, misal: /blog/halaman-ngawur.

    • Halaman tetap jalan dan judulnya mengikuti: Judul Post: halaman-ngawur.

Inilah kekuatan Dynamic Routing. Satu file untuk menangani ribuan kemungkinan URL.


5. Apa yang Dipelajari di Hari Kedua

Selamat! Hari ini kamu sudah menguasai 3 pilar penting:

  1. Link Component: Navigasi cepat tanpa refresh.

  2. Layout (Navbar): Membuat menu yang konsisten di semua halaman.

  3. Dynamic Routing ([slug]): Membuat halaman fleksibel yang isinya berubah sesuai URL.

6. Latihan Mandiri

Agar semakin paham, coba tantangan kecil ini:

  1. Tambahkan menu "Contact" di Navbar (layout.tsx).

  2. Buat halaman src/app/contact/page.tsx yang isinya biodata singkat kamu.

  3. Pastikan tombol Contact di menu bisa diklik dan mengarah ke halaman yang benar.

Comments

Popular posts from this blog

Why Your React App Shows a Blank Page (And How to Fix It)

Introduction One of the most frustrating problems when working with React JS is opening your app and seeing… nothing . No error message. No UI. Just a blank page . This issue happens frequently, especially after deployment or routing changes. In this article, we’ll explain why React apps show a blank page , the most common causes , and how to fix them step by step . What a “Blank Page” Usually Means in React A blank page usually means: React failed to render the UI JavaScript error stopped execution Routing or build configuration is broken Most of the time, the issue is not React itself , but how the app is configured. 1. JavaScript Error in the Console The first thing you should always check is the browser console. How to Check Open the app Right click → Inspect Open the Console tab If you see a red error message, React stopped rendering. Common Examples Cannot read property of undefined Unexpected token Module not found Fix Read the...

More Common React JS Mistakes Developers Still Make (And How to Avoid Them)

  Introduction Even after learning the basics of React JS, many developers continue to make mistakes that hurt performance, readability, and scalability. These are not beginner-only errors — they often appear in real projects, especially when apps start to grow. In this article, we’ll look at common React JS mistakes developers still make , explain why they happen , and show better patterns to avoid long-term problems. 1. Re-Creating Functions on Every Render Many developers define functions directly inside components without realizing the impact. ❌ Common Pattern function App ( ) { const handleClick = ( ) => { console . log ( "clicked" ); }; return < Button onClick = {handleClick} />; } While this works, the function is re-created on every render . ✅ Better Approach (When Needed) const handleClick = useCallback ( () => { console . log ( "clicked" ); }, []); Why This Matters Causes unnecessary re-renders Affects per...

Nginx vs Apache: Which Web Server Should You Use on a VPS?

Introduction When setting up a VPS for hosting websites or applications, one of the first decisions you’ll face is choosing a web server. The two most popular options are Nginx and Apache . Both are powerful, widely used, and production-ready — but they work very differently. In this article, we’ll compare Nginx vs Apache , explain how each one works , highlight their strengths and weaknesses , and help you decide which web server is better for your VPS setup . What Is a Web Server? A web server is software that: Receives requests from browsers Processes those requests Serves HTML, CSS, JavaScript, or API responses Popular web servers include: Nginx Apache LiteSpeed Caddy Among them, Nginx and Apache dominate most VPS environments . What Is Apache? Apache has been around since the mid-1990s and was the most widely used web server for many years. How Apache Works Apache uses a process-based or thread-based model : Each request is handled by a p...