Beginner’s Guide to Setting Up React Router DOM 🧭

By Umayer Emon

/

June 15, 2025

Web Development



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-dom

πŸ—‚οΈ Step 2: Basic File Structure

Organise your components/pages like this:

css

/src
  β”œβ”€β”€ App.jsx
  β”œβ”€β”€ main.jsx
  └── pages/
       β”œβ”€β”€ Home.jsx
       β”œβ”€β”€ About.jsx
       └── Contact.jsx

πŸ“ Step 3: Setting Up Routes

In 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;

🧩 Step 4: Using Layouts with Outlet

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>
} />

βœ… Conclusion

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.

Search Anything

Recent Blogs

Categories