DEV Community

Divam Jain
Divam Jain

Posted on

How to Centralize Routes in React Like a Pro (Beginner-Friendly Guide)

1. Why Centralize Routes in React?

Have you ever opened a React project and found a giant, messy App.jsx cluttered with dozens of routes? Or struggled to manage different user roles (like admin vs. regular users) because routes were scattered everywhere?

Centralizing your routes solves these problems by:

  • Keeping your code clean
  • Making maintenance easier
  • Improving scalability
  • Supporting role-based routing

2. Prerequisites

Before we dive into centralizing routes in React, make sure you have these basics covered:

React Fundamentals

  • Familiarity with components, JSX, and props.
    If you're new, check out the Learn React documentation

  • React Router Installed
    This guide uses react-router-dom v6+.

Install it in your project:

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode
  • A React Project Set Up
    Use create-react-app, Vite, or your preferred setup.

  • Basic Understanding of Routing
    Know how , , and work.

That’s it! If you have these ready, you’re all set to follow along.

3. Step-by-Step Implementation

A. Folder Structure

src/
├── router/
│   ├── UserRoutes.jsx
│   ├── AdminRoutes.jsx
│   └── AllRoutes.jsx
Enter fullscreen mode Exit fullscreen mode

B. Create Route Files

UserRoutes.jsx

const UserRoutes = [
   {
     path:"/",
     element:<Home/>
  },
  {
    path: "/dashboard",
    element: <UserDashboard />
  },
  {
    path: "/profile",
    element: <UserProfile />
  }
];

export default UserRoutes;
Enter fullscreen mode Exit fullscreen mode

Similarly create AdminRoutes.jsx as UserRoutes.jsx is created

C. Combine Routes

AllRoutes.jsx

import UserRoutes from './UserRoutes';
import AdminRoutes from './AdminRoutes';
import { Routes,Route} from 'react-router-dom'
const IndexRoutes=[...UserRoutes,...AdminRoutes]

const AllRoutes=()=>{
return (
    <Routes>
        {IndexRoutes.map((item,index)=>(
          <Route key={index} path={item.path} element={item.element}/>
        ))}
    </Routes>
  )
}
Enter fullscreen mode Exit fullscreen mode

D._ Implement in App.jsx_

import { BrowserRouter, Routes, Route } from 'react-router-dom';
import AllRoutes from './router/AllRoutes';

function App() {
  return (
    <BrowserRouter>
      <AllRoutes/>
    </BrowserRouter>
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)