Simple Tutorials for Smart Learning
React Router is a popular library used for adding navigation and routing capabilities to React applications. It allows you to:
To use React Router, install the library via npm or yarn:
npm install react-router-dom
Or, if you use yarn:
yarn add react-router-dom
BrowserRouter
Routes
Route
import React from 'react'; import { BrowserRouter, Routes, Route } from 'react-router-dom'; function Home() { return <h1>Home Page</h1>; } function About() { return <h1>About Page</h1>; } function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </BrowserRouter> ); } export default App;
Explanation:
React Router provides the Link and NavLink components for navigation.
Link
NavLink
import { Link } from 'react-router-dom'; function Navbar() { return ( <nav> <Link to="/">Home</Link> | <Link to="/about">About</Link> </nav> ); }
The NavLink adds styling to indicate the active link.
import { NavLink } from 'react-router-dom'; function Navbar() { return ( <nav> <NavLink to="/" activeClassName="active"> Home </NavLink>{' '} |{' '} <NavLink to="/about" activeClassName="active"> About </NavLink> </nav> ); }
Example with Navbar
function App() { return ( <BrowserRouter> <Navbar /> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </BrowserRouter> ); }
Dynamic routing is useful for creating routes with parameters, such as user profiles or product details.
Use the : syntax to define a dynamic segment in the path.
:
function Product({ params }) { const { id } = params; return <h1>Product ID: {id}</h1>; } function App() { return ( <BrowserRouter> <Routes> <Route path="/product/:id" element={<Product />} /> </Routes> </BrowserRouter> ); }
React Router’s useParams hook retrieves the dynamic values.
useParams
import { useParams } from 'react-router-dom'; function Product() { const { id } = useParams(); return <h1>Product ID: {id}</h1>; }
import React from 'react'; import { BrowserRouter, Routes, Route, Link, useParams } from 'react-router-dom'; function ProductList() { const products = [ { id: 1, name: 'Product A' }, { id: 2, name: 'Product B' }, ]; return ( <ul> {products.map((product) => ( <li key={product.id}> <Link to={`/product/${product.id}`}>{product.name}</Link> </li> ))} </ul> ); } function Product() { const { id } = useParams(); return <h1>Details for Product ID: {id}</h1>; } function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<ProductList />} /> <Route path="/product/:id" element={<Product />} /> </Routes> </BrowserRouter> ); } export default App;
React.lazy
Suspense
*
<Route path="*" element={<NotFound />} />