Proper Usage of <Link>
in React Router
A common mistake in React Router applications is using incorrect paths with the <Link>
component, which can lead to broken navigation or unexpected behavior.
The Problem: Incorrect Paths in <Link>
// ❌ Common mistakes:
// 1. Missing leading slash
<Link to="about">About</Link>
// 2. Absolute path when relative was intended
<Link to="/users/profile">Profile</Link>
// 3. Malformed paths
<Link to="users//profile">Profile</Link>
Why Proper Paths Matter
- Consistent Navigation: Ensures reliable routing behavior
- Relative vs Absolute: Affects how routes are resolved
- Nested Routes: Impacts route matching in nested structures
- Error Prevention: Avoids failed navigations
Correct Implementation
1. Absolute Paths (Recommended for Top-Level)
<Link to="/about">About</Link> // ✅ Absolute path
2. Relative Paths (For Nested Routes)
function UserProfile() {
return (
<div>
<Link to="settings">Settings</Link> // ✅ Relative to current route
</div>
);
}
// When rendered at /users/123, links to /users/123/settings
3. Dynamic Paths
<Link to={`/users/${userId}`}>User Profile</Link> // ✅ Dynamic path
4. Path Objects (Advanced)
<Link
to={{
pathname: "/users",
search: "?sort=name",
hash: "#details"
}}
>
Users
</Link>
Common Path Patterns
Use Case | Example | Notes |
---|---|---|
Home | / | Always include leading slash |
Nested | users/profile | Relative to parent route |
Dynamic | users/:id | Use params in routes |
Query Strings | users?sort=name | Access via useSearchParams |
Hash Links | #section | For page anchors |
Best Practices
- Be Explicit: Prefer absolute paths for clarity
- Match Route Definitions: Ensure paths match your
<Route>
configurations - Use Type Safety (TypeScript):
type AppRoutes = "/" | "/about" | "/users" | `/users/${string}`;
const MyLink = ({ to }: { to: AppRoutes }) => (
<Link to={to}>Link</Link>
);
- Test Navigation: Verify links work in all contexts
- Handle Dynamic Segments Carefully: Validate variables before using in paths
Debugging Tips
- Check Route Definitions: Ensure paths match between
<Link>
and<Route>
- Inspect Current Location:
const location = useLocation();
console.log(location.pathname);
- Verify Nested Routes: Use
<Outlet>
properly in parent components - Test Relative Paths: Remember they’re relative to current URL
Migration from v5 to v6
In React Router v6, relative links are more intuitive:
// In v5 (more complex)
<Link to={match.url + "/details"}>
// In v6 (simpler)
<Link to="details">
Remember: Proper path construction in <Link>
components is crucial for reliable navigation. Always verify your paths match your route configuration and consider using TypeScript for additional path safety.