Hassan Agmir Hassan Agmir

How to Configure React Router in React App

Hassan Agmir
How to Configure React Router in React App

React Router is an essential library for managing navigation and routing in React applications. With the release of React Router v7, significant improvements have been introduced, making routing more efficient, flexible, and easier to manage. This guide will walk you through configuring React Router v7 in your React project step by step.

1. Installing React Router v7

Before setting up routing in your project, you need to install React Router v7. If you are starting from scratch, create a new React project using Vite (recommended for speed and performance):

npx create-vite@latest my-react-router-app --template react
cd my-react-router-app
npm install

Then, install React Router v7:

npm install react-router-dom@latest

This will add the necessary dependencies for routing in your React project.

2. Setting Up the Router

After installation, wrap your application with the BrowserRouter component to enable routing. Open your main.jsx (or index.js in a non-Vite project) and modify it as follows:

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

3. Defining Routes

In your App.jsx, use the Routes and Route components to define your application's routes:

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 (
    <div>
      <h1>Welcome to My React App</h1>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
    </div>
  );
}

export default App;

Each Route component maps a URL path to a corresponding component, allowing navigation within the application.

4. Implementing Navigation

Instead of using traditional anchor (<a>) tags, which trigger full page reloads, use the Link component from React Router:

import { Link } from 'react-router-dom';

function Navbar() {
  return (
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
      <Link to="/contact">Contact</Link>
    </nav>
  );
}

export default Navbar;

Now, include Navbar in App.jsx:

import Navbar from './components/Navbar';

function App() {
  return (
    <div>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
    </div>
  );
}

5. Handling Nested Routes

Nested routes allow hierarchical navigation structures. Modify App.jsx to include nested routes:

import { Routes, Route } from 'react-router-dom';
import Dashboard from './pages/Dashboard';
import DashboardHome from './pages/DashboardHome';
import DashboardSettings from './pages/DashboardSettings';

function App() {
  return (
    <Routes>
      <Route path="/dashboard" element={<Dashboard />}>
        <Route index element={<DashboardHome />} />
        <Route path="settings" element={<DashboardSettings />} />
      </Route>
    </Routes>
  );
}

export default App;

Inside the Dashboard.jsx file, add an Outlet to render child components:

import { Outlet } from 'react-router-dom';

function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
      <Outlet />
    </div>
  );
}

export default Dashboard;

6. Redirects and Error Handling

React Router v7 allows handling redirects using the Navigate component:

import { Navigate } from 'react-router-dom';

function NotFound() {
  return <Navigate to="/" replace />;
}

To handle errors, create an ErrorPage.jsx component:

function ErrorPage() {
  return (
    <div>
      <h2>404 - Page Not Found</h2>
      <p>The page you are looking for does not exist.</p>
    </div>
  );
}

export default ErrorPage;

Then, define a catch-all route in App.jsx:

<Route path="*" element={<ErrorPage />} />

7. Fetching Data with Loaders

React Router v7 introduces loaders for pre-fetching data before rendering components:

import { useLoaderData } from 'react-router-dom';

function Home() {
  const data = useLoaderData();
  return <div>{data.message}</div>;
}

Define the loader in the router configuration:

const router = createBrowserRouter([
  {
    path: '/',
    element: <Home />,
    loader: async () => {
      return { message: 'Welcome to React Router v7!' };
    },
  },
]);

8. Enabling Server-Side Rendering (SSR)

React Router v7 supports SSR, allowing preloading data on the server before rendering:

import { createRouter } from 'react-router-dom/server';

export const router = createRouter([
  {
    path: '/',
    element: <Home />,
    loader: async () => fetchDataFromAPI(),
  },
]);

Conclusion

React Router v7 simplifies routing in React applications with enhanced features like nested routes, loaders, and SSR support. Following this guide, you can set up a well-structured routing system in your React projects, improving navigation and user experience.

Subscribe to my Newsletters

Stay updated with the latest programming tips, tricks, and IT insights! Join my community to receive exclusive content on coding best practices.

© Copyright 2025 by Hassan Agmir . Built with ❤ by Me