In modern web applications, routing plays a key role in managing navigation and rendering components based on the URL. React Router is the most popular library for handling routing in React apps.
Letβs walk through a simple example to get you started with routing in React using react-router-dom
.
π¦ Step 1: Install React Router
First, add the React Router dependency to your project:
bash
npm install react-router-dom
This will install everything needed to handle routing in your React app.
π§ Step 2: Create Components
Letβs define a few components to simulate different pages in your application.
jsx
// Home.js
const Home = () => <h2>π Home Page</h2>;
// About.js
const About = () => <h2>βΉοΈ About Page</h2>;
// Contact.js
const Contact = () => <h2>π Contact Page</h2>;
Each of these components will be displayed based on the current URL path.
π Step 3: Set Up Routing in App.js
Here's how to set up basic routing in your React app:
jsx
// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom';
const Home = () => <h2>π Home Page</h2>;
const About = () => <h2>βΉοΈ About Page</h2>;
const Contact = () => <h2>π Contact Page</h2>;
function App() {
return (
<Router>
<div>
<nav style={{ padding: '10px', backgroundColor: '#f0f0f0' }}>
<Link to="/" style={{ margin: '0 10px' }}>Home</Link>
<Link to="/about" style={{ margin: '0 10px' }}>About</Link>
<Link to="/contact" style={{ margin: '0 10px' }}>Contact</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</div>
</Router>
);
}
export default App;
π How This Works
π <Router>
Wraps your app and enables routing.
π <Link>
Acts like an anchor tag (<a>
) but prevents full page reload. Used for in-app navigation.
π <Routes>
and <Route>
<Routes>
replaces the old <Switch>
(React Router v6+).<Route>
maps a URL path to a specific component using element={<Component />}
.
π Step 4: Run the App
Start the development server:
bash
npm start
Now visit:
/
β Home/about
β About/contact
β Contact
And use the nav links to switch between themβall without refreshing the page.
π Summary
With just a few lines of code, youβve set up React Router in your application:
β
Installed react-router-dom
β
Created page components
β
Configured routes using <Routes>
and <Route>
β
Linked pages with <Link>
π§ Bonus Tips
jsx
<Route path="*" element={<NotFound />} />
- For nested routes or layouts, you can combine
<Outlet />
with parent routes. - For route parameters, use
useParams()
from react-router-dom
.
React Router makes it easy to build single-page applications that feel seamless and dynamic. Whether youβre building a simple site or a large web app, itβs an essential tool in the React ecosystem