
As a beginner in React, one of the first powerful tools you'll learn is React Router DOM β it lets you create a multi-page experience in a single-page app. In this blog, Iβll walk you through how I set up routing in my React projects using React Router DOM v6+.
π§ Step 1: Installation
To get started, install React Router:
npm install react-router-domOrganise your components/pages like this:
css
/src
βββ App.jsx
βββ main.jsx
βββ pages/
βββ Home.jsx
βββ About.jsx
βββ Contact.jsxIn your main.jsx:
main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')).render(
<BrowserRouter>
<App />
</BrowserRouter>
);Then in App.jsx:
App.jsx
import { Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
);
}
export default App;If you want a common layout (like NavBar and Footer), use a layout route:
import { Outlet } from 'react-router-dom';
import NavBar from './components/NavBar';
function MainLayout() {
return (
<>
<NavBar />
<Outlet />
</>
);
}Then wrap your routes:
<Route path="/" element={<MainLayout />}>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
<Route path="contact" element={<Contact />} />
</Route>
π Bonus: Protected Routes (Simple Example)
const PrivateRoute = ({ children }) => {
const isAuthenticated = true; // Replace with real auth check
return isAuthenticated ? children : <Navigate to="/login" />;
};
<Route path="/dashboard" element={
<PrivateRoute>
<Dashboard />
</PrivateRoute>
} />React Router DOM helps you build real-world, multi-page apps easily. Understanding routes, Outlet, and route protection early on will make your projects more scalable.