To add client-side routing to a React application scaffolded with Vite, you typically install react-router-dom and restructure your entry point to use BrowserRouter and Routes. This allows you to define which component renders to each URL path, including dynamic segments.
Below we walk through converting a simple main.jsx file that renders only a Login component into one that supports:
- Root path (
/) or/login→ shows theLogincomponent - Any other
/{moduleName}→ renders a dynamic component (e.g., dashboard, report) - Unmatched paths → custom 404 page
Step 1: Instal the routing libray
npm install react-router-dom
Step 2: Rewrite main.jsx
Instead of directly rendering the Login component, wrap your app in BrowserRouter and define Routes:
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import './index.css';
import SignIn from './pages/SignIn.jsx'; // renamed from Login
import DynamicModule from './pages/DynamicModule.jsx';
import NotFound from './pages/NotFound.jsx';
createRoot(document.getElementById('root')).render(
<StrictMode>
<BrowserRouter>
<Routes>
{/* Redirect root to /signin */}
<Route path="/" element={<Navigate to="/signin" replace />} />
<Route path="/signin" element={<SignIn />} />
{/* Dynamic segment – matches any single path segment like /dashboard */}
<Route path="/:moduleName" element={<DynamicModule />} />
{/* Catch-all for undefined routes */}
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
</StrictMode>
);
Notice the use of replace in the Navigate component to avoid adding a history entry for the redirect.
Step 3: Build the dynamic module page
Create src/pages/DynamicModule.jsx:
import { useParams } from 'react-router-dom';
const DynamicModule = () => {
const { moduleName } = useParams();
return (
<div>
<h1>Module: {moduleName}</h1>
</div>
);
};
export default DynamicModule;
Step 4: Create the 404 page
// src/pages/NotFound.jsx
const NotFound = () => (
<div>
<h1>404 – Page not found</h1>
</div>
);
export default NotFound;
How it works
/in the browser address bar triggers a redirect to/signin./signindisplays theSignIncomponent./dashboard,/settings, or any other single‑segment path shows theDynamicModulecomponent, which reads the segment value viauseParams.- Any path that doesn't match the above patterns (e.g.,
/admin/users) displays the 404 page.
You can extend this pattern by adding more specific routes before the dynamic one, so they take precedence.