Routing is a core part of any React application — it lets users navigate between pages like “Home,” “About,” or “Profile” without a full page reload. In this tutorial, we’ll build a basic React app with React Router v6, the standard library for client-side routing.
Prerequisites
Before we start make sure that you have Node.js installed
Set Up Your React App
You can use Vite for fast setup or feel free to create a new empty project by yourself:
npm create vite@latest react-router-demo --template react
cd react-router-demo
npm install
Then install React Router:
npm install react-router-dom
Project Structure
Here’s what we’ll create:
src/
pages/
Home.jsx
About.jsx
Contact.jsx
App.jsx
main.jsx
Create Example Pages
pages/Home.jsx
export default function Home() {
return <h2> Welcome to the Home Page</h2>;
}
pages/About.jsx
export default function About() {
return <h2> About Us</h2>;
}
pages/Contact.jsx
export default function Contact() {
return <h2> Contact Us</h2>;
}
Set Up Routing in App.jsx
Now wire up routes using BrowserRouter
, Routes
, and Route
.
src/App.jsx
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
import Contact from "./pages/Contact";
function App() {
return (
<BrowserRouter>
<nav style={{ display: "flex", gap: "1rem", padding: "1rem" }}>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</BrowserRouter>
);
}
export default App;
Render the App
Make sure main.jsx
renders the App
:
src/main.jsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
That’s It!
Now you have:
- Navigation links (Home, About, Contact)
- URL routing (
/
,/about
,/contact
) - No full-page reloads
Try visiting the URLs manually or clicking the links — routing just works!
Bonus: Add a 404 Page
To catch unknown routes:
<Route path="*" element={<h2>404 - Page Not Found</h2>} />
Add it after the other routes in your <Routes>
block.
Conclusion
With just a few lines of code, you’ve set up:
- React Router for SPA-style navigation
- Multiple pages with real URLs
- A maintainable page structure
This forms the base of any real-world React app.