React Router Tutorial
Key Concepts
- BrowserRouter
- Routes
- Route
- Link
- useNavigate
BrowserRouter
BrowserRouter is a context provider that wraps your entire application, enabling routing functionality. It uses the HTML5 history API to keep the UI in sync with the URL.
Example:
import { BrowserRouter } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<div>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</div>
</BrowserRouter>
);
}
Routes
Routes is a container for multiple Route components. It determines which Route to render based on the current URL.
Example:
import { Routes, Route } from 'react-router-dom';
function App() {
return (
<div>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</div>
);
}
Route
Route is a component that maps a URL path to a specific component. It defines what should be rendered when the URL matches the specified path.
Example:
import { Route } from 'react-router-dom';
function App() {
return (
<div>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</div>
);
}
Link
Link is a component that provides declarative, accessible navigation around your application. It prevents the page from reloading and updates the URL.
Example:
import { Link } from 'react-router-dom';
function Navigation() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
);
}
useNavigate
useNavigate is a hook that returns a function allowing you to navigate programmatically. It is useful for handling navigation in response to events.
Example:
import { useNavigate } from 'react-router-dom';
function LoginButton() {
const navigate = useNavigate();
const handleLogin = () => {
// Perform login logic
navigate('/dashboard');
};
return (
<button onClick={handleLogin}>Login</button>
);
}
Analogies
Think of BrowserRouter as a GPS system that guides your application. Routes are like the different routes you can take, and Route is like a specific destination on the map. Link is like a clickable button on the GPS that takes you to a new destination, and useNavigate is like a voice command that tells the GPS to take you to a specific place.
Another analogy is a library. BrowserRouter is the library itself, Routes are the different sections (fiction, non-fiction), Route is a specific book on the shelf, Link is a sign pointing to a section, and useNavigate is a librarian who can take you directly to the book you want.