Nearby lessons
36 of 44🛣️ React Router – Absolute & Relative Path
📌 What are Paths?
Absolute vs Relative Path in React Router
When defining routes or navigation in React Router, we can use either absolute paths or relative paths. Understanding the difference is important to avoid unexpected behavior in your app.
📌 What is an Absolute Path?
- An absolute path starts with a forward slash /
- It always constructs the route from the root of the app
- Does not depend on the current URL
- Useful when you want to always navigate to a specific route regardless of current location
React Playground
import { BrowserRouter, Routes, Route, Link } from "react-router-dom"; function Home() { return <h1>🏠 Home Page</h1>; } function About() { return <h1>ℹ️ About Page</h1>; } export default function App() { return ( <BrowserRouter> <nav> {/* Absolute paths start with / */} <Link to="/about">Go to About</Link> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </BrowserRouter> ); }
📌 What is a Relative Path?
- A relative path does not start with /
- It inherits from the closest parent route
- Constructs the path based on the current URL
- Useful for nested routes and links
React Playground
import { BrowserRouter, Routes, Route, Link, Outlet } from "react-router-dom"; function Layout() { return ( <div> <h1>🏠 Home Layout</h1> <nav> {/* ✅ Relative path navigation */} <Link to="dashboard">Go to Dashboard</Link> </nav> <Outlet /> </div> ); } function Dashboard() { return ( <div> <h2>📊 Dashboard</h2> <nav> {/* ✅ Relative path (no leading /) */} <Link to="stats">Go to Stats</Link> </nav> <Outlet /> </div> ); } function Stats() { return <h3>📈 Dashboard Stats</h3>; } export default function App() { return ( <BrowserRouter> <Routes> {/* Root route */} <Route path="/" element={<Layout />}> {/* Nested relative route */} <Route path="dashboard" element={<Dashboard />}> <Route path="stats" element={<Stats />} /> </Route> </Route> </Routes> </BrowserRouter> ); }
⚖️ Difference Between Absolute and Relative Path
- Relative paths don’t start with /
- Absolute paths start with /
- Relative paths will inherit the closest route
- Absolute paths will always construct the route from the root
🧠 Test Your Knowledge
3 QuestionsProgress: 0 / 3
Keep Going!React - Axios for API Calls