If you haven't installed React Router yet, run this command in your project directory:
npm install react-router-dom
First, make sure you have components for your pages:
-
LoginPage
.tsx -
ServicesPage.tsx
-
AboutPage.tsx
LoginPage.tsx
import React from 'react';
const LoginPage: React.FC = () => {
return <h2>This is the Login Page</h2>;
};
export default LoginPage;
ServicesPage.js
import React from 'react';
function ServicesPage() {
return <h2>This is the Services Page</h2>;
}
export default ServicesPage;
AboutPage.js
import React from 'react';
const AboutPage: React.FC = () => {
return <h2>This is the About Page</h2>;
};
export default AboutPage;
Create a new file called AppRoutes.tsx
nand define all your routes there.
import React from 'react';
import {Route, Routes} from 'react-router-dom';
import LoginPage from "./pages/LoginPage";
import ServicesPage from "./pages/ServicesPage";
import AboutPage from "./pages/AboutPage";
interface RouteProps {
exact?: boolean;
path: string;
component: React.ComponentType<any>;
}
const AppRoutes: React.FC = () => {
return (
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/services" element={<ServicesPage />} />
<Route path="/about" element={<AboutPage />} />
{/* Default route */}
<Route path="/" element={<LoginPage />} />
</Routes>
);
};
export default AppRoutes;
Now you can import AppRoutes
into your main App.tsx
file.
import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import AppRoutes from './app.routes'; // Import your routes
import { Link } from 'react-router-dom';
const App: React.FC = () => {
return (
<div>
{/* Navigation */}
<nav>
<ul>
<li><Link to="/login">Login</Link></li>
<li><Link to="/services">Services</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
</nav>
{/* Render Routes */}
<AppRoutes />
</div>
);
};
export default App;
-
app.routes.tsx
: Contains all your route definitions using theSwitch
andRoute
components. -
App.tsx
: Now imports and uses theAppRoutes
component to manage routing in a more organized and modular way.
You can add a default route to redirect the user to a specific page if they visit the root (/
):
<Route exact path="/" component={LoginPage} />
Start your development server:
npm start
Now, you can navigate to /login
, /services
, and /about
to see each page.
This is a basic routing setup for your React app with login_page
, services_page
, and about_page
.
OUTPUT
TEST:
https://react-router-thirdy.web.app/login
GITHUB: