Relative Navigation: Going Back or Up
What you'll learn: How to navigate using relative paths and browser history to move backward or upward through your route hierarchy.
Sometimes you don't want to specify the full path when navigating—you just want to go "back" to where the user came from, or move "up" one level in your nested route structure. React Router gives you two powerful patterns for this.
Going Back with History
The navigate function accepts -1 to go back one entry in the browser history, like clicking the browser's back button:
import { useNavigate } from 'react-router-dom';
function ProductDetail() {
const navigate = useNavigate();
return (
<button onClick={() => navigate(-1)}>
← Back
</button>
);
}
You can use any negative number: navigate(-2) goes back twice, and so on. Positive numbers go forward in history if available.
Going Up with Relative Paths
In nested routes, use .. to navigate up one level in the route hierarchy—similar to filesystem navigation:
// Currently at: /products/electronics/laptop-123
function ProductPage() {
const navigate = useNavigate();
// Goes to: /products/electronics
return (
<button onClick={() => navigate('..')}>
Back to Category
</button>
);
}
Important: By default, .. removes one path segment. To navigate relative to the route hierarchy instead, pass { relative: 'route' }:
navigate('..', { relative: 'route' }); // Up one route level
navigate('..', { relative: 'path' }); // Up one URL segment (default)
Key Takeaway: Use navigate(-1) to go back in browser history, or navigate('..') to move up in your route structure—giving users intuitive navigation without hardcoding full paths.