Berikut materi yang lebih terstruktur, rapi, dan tetap mudah dipahami untuk bagian:
🔹 Cara Lebih Rapi (Routing Dipisah)
🎯 Tujuan
Supaya project React:
- Lebih rapi
- Mudah dibaca
- Mudah dikembangkan
📌 Kenapa Routing Dipisah?
Kalau semua ditaruh di App.js, nanti:
- File jadi panjang ❌
- Susah dibaca ❌
- Susah dikembangkan ❌
Solusinya: pisahkan routing ke file khusus
📁 Struktur Folder yang Disarankan
src/
│
├── pages/
│ ├── Home.jsx
│ ├── About.jsx
│ └── Contact.jsx
│
├── routes/
│ └── index.js
│
└── App.js
🧱 1. Buat File Routing
Buat file:
📄 src/routes/index.js
Isi:
import { Routes, Route } from "react-router-dom";
import Home from "../pages/Home";
import About from "../pages/About";
import Contact from "../pages/Contact";
function AppRoutes() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
);
}
export default AppRoutes;
🔌 2. Hubungkan ke App.js
Edit App.js:
import { BrowserRouter } from "react-router-dom";
import AppRoutes from "./routes";
function App() {
return (
<BrowserRouter>
<AppRoutes />
</BrowserRouter>
);
}
export default App;
🧠 Penjelasan Alur
BrowserRouter→ mengaktifkan routingAppRoutes→ berisi daftar semua halamanRoute→ menentukan URL dan halaman
🔄 Alur Sederhana
User buka URL → App.js → AppRoutes → Halaman tampil
Contoh:
/→ Home/about→ About/contact→ Contact
✅ Keuntungan Cara Ini
- Kode lebih bersih ✔
- Mudah tambah halaman baru ✔
- Cocok untuk project besar ✔
➕ Contoh Tambah Halaman Baru
Misalnya tambah halaman Profile
1. Buat file:
📄 pages/Profile.jsx
function Profile() {
return <h1>Ini Halaman Profile</h1>;
}
export default Profile;
2. Tambahkan di routes:
import Profile from "../pages/Profile";
<Route path="/profile" element={<Profile />} />
🎯 Tips Penting
- Nama file bebas, tapi usahakan jelas (
routes,router) - Simpan semua route di satu tempat
- Biasakan struktur dari awal (biar tidak berantakan nanti)
🧩 Ringkasan
- Routing tidak harus di App.js
- Lebih baik dipisah ke folder
routes App.jscukup jadi "pembungkus utama"