🧭 Route / Link / Navigate
React Router gives you powerful tools to build multi-page apps using routes, links, and programmatic navigation.
🛤️ 1. Route
Use <Route>
inside <Routes>
to define which component renders at each path.
import { Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
);
}
🔗 2. Link
Replace anchor tags with <Link>
to enable client-side navigation without reloading.
import { Link } from 'react-router-dom';
function Navbar() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
);
}
➡️ 3. Navigate (Programmatic Navigation)
Use useNavigate()
to navigate via code — helpful after form submission or button click.
import { useNavigate } from 'react-router-dom';
function LoginButton() {
const navigate = useNavigate();
const handleLogin = () => {
// Assume login logic is done
navigate('/dashboard');
};
return <button onClick={handleLogin}>Login</button>;
}
These three features make routing flexible and user-friendly in any React app.