Kembali ke Blog
Cara Menggunakan React Router untuk Navigation
React Router adalah library standard untuk routing di React applications. Mari pelajari cara implementasinya.
Installation
Install React Router
npm install react-router-dom
Basic Setup
Router Configuration
// App.jsx
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
import Contact from "./pages/Contact";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</BrowserRouter>
);
}
Navigation Components
Link Component
import { Link } from "react-router-dom";
function Navbar() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
);
}
NavLink for Active States
import { NavLink } from "react-router-dom";
function Navbar() {
return (
<nav>
<NavLink to="/" className={({ isActive }) => (isActive ? "active" : "")}>
Home
</NavLink>
</nav>
);
}
Dynamic Routes
URL Parameters
// Route definition
<Route path="/blog/:slug" element={<BlogPost />} />;
// Accessing params
import { useParams } from "react-router-dom";
function BlogPost() {
const { slug } = useParams();
return <h1>Post: {slug}</h1>;
}
Multiple Parameters
<Route path="/category/:categoryId/product/:productId" element={<Product />} />;
function Product() {
const { categoryId, productId } = useParams();
return (
<div>
<p>Category: {categoryId}</p>
<p>Product: {productId}</p>
</div>
);
}
Nested Routes
Layout Pattern
// App.jsx
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
<Route path="dashboard" element={<Dashboard />}>
<Route index element={<DashboardHome />} />
<Route path="settings" element={<Settings />} />
</Route>
</Route>
</Routes>
Outlet Component
import { Outlet } from "react-router-dom";
function Layout() {
return (
<div>
<Navbar />
<main>
<Outlet /> {/* Child routes render here */}
</main>
<Footer />
</div>
);
}
Programmatic Navigation
useNavigate Hook
import { useNavigate } from "react-router-dom";
function LoginForm() {
const navigate = useNavigate();
const handleSubmit = (e) => {
e.preventDefault();
// Login logic...
navigate("/dashboard");
};
return <form onSubmit={handleSubmit}>{/* form fields */}</form>;
}
Navigate with State
navigate("/product", { state: { from: "homepage" } });
// Access state
import { useLocation } from "react-router-dom";
function Product() {
const location = useLocation();
console.log(location.state?.from);
}
Protected Routes
Auth Guard
import { Navigate } from "react-router-dom";
function ProtectedRoute({ children }) {
const isAuthenticated = useAuth();
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return children;
}
// Usage
<Route
path="/dashboard"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>;
404 Page
Catch-All Route
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} />
</Routes>;
function NotFound() {
return <h1>404 - Page Not Found</h1>;
}
Query Parameters
useSearchParams
import { useSearchParams } from "react-router-dom";
function SearchPage() {
const [searchParams, setSearchParams] = useSearchParams();
const query = searchParams.get("q");
const updateSearch = (newQuery) => {
setSearchParams({ q: newQuery });
};
return (
<div>
<p>Searching for: {query}</p>
</div>
);
}
Lazy Loading Routes
Code Splitting
import { lazy, Suspense } from "react";
const Dashboard = lazy(() => import("./pages/Dashboard"));
function App() {
return (
<Routes>
<Route
path="/dashboard"
element={
<Suspense fallback={<Loading />}>
<Dashboard />
</Suspense>
}
/>
</Routes>
);
}
Kesimpulan
React Router menyediakan routing solution yang powerful dan flexible untuk React applications dengan support untuk nested routes, protected routes, dan lazy loading.
Ditulis oleh
Hendra Wijaya
Artikel Sebelumnya
Cara Menggunakan Notion untuk Produktivitas
Artikel Selanjutnya
Cara Menggunakan Redis untuk Caching