Routing
Navigating between pages
10-15 min
Routing in React
Routing is essential for building multi-page React applications. React Router is the standard library for handling navigation in React.
Installing React Router
npm install react-router-dom
Basic Setup
Setting up the router
import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</BrowserRouter>
);
}
Navigating between pages
import { Link } from 'react-router-dom';
function Navigation() {
return (
<nav>
<Link to="/">Accueil</Link>
<Link to="/about">À propos</Link>
<Link to="/contact">Contact</Link>
</nav>
);
}
Dynamic Routes
Routes with parameters
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/users/:id" element={<UserProfile />} />
<Route path="/products/:category/:id" element={<ProductDetails />} />
</Routes>
</BrowserRouter>
);
}
// Dans le composant UserProfile
function UserProfile() {
const { id } = useParams();
return <div>Profil de l'utilisateur {id}</div>;
}
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion