React Router is a powerful library for routing in React applications. It allows developers to build single-page applications (SPAs) with dynamic navigation and routing capabilities, enabling the display of different components or views based on the current URL. In this post, I will cover how to integrate React Router in a React project.
Create the React App npm create vite@latest . -- --template react-ts npm install
Installing React Router npm install react-router@latest --save
Add MainLayout and Sidebar src/layouts/MainLayout.tsx
import Sidebar from "./Sidebar.tsx" ; import {Outlet } from "react-router" ; function MainLayout ( ) { return ( <div > <div style ={{display: 'flex ', minHeight: '100vh '}}> <Sidebar /> <div style ={{flex: 1 , padding: '20px '}}> {/* Main content area */} <Outlet /> </div > </div > </div > ); } export default MainLayout ;
src/layouts/Sidebar.tsx
import {NavLink } from "react-router" ; import {useEffect, useState} from "react" ; async function fetchMenuItems ( ) { return [ {title : 'Home' , path : '/' }, {title : 'About' , path : '/about' }, {title : 'Contact' , path : '/contact' }, ]; } function Sidebar ( ) { const [menuItems, setMenuItems] = useState<{ title : string ; path : string }[]>([]); useEffect (() => { const getMenuItems = async ( ) => { const items = await fetchMenuItems (); setMenuItems (items); }; getMenuItems (); }, []); return ( <nav style ={{width: '250px ', background: '#282c34 ', color: 'white ', padding: '20px ',}}> <ul style ={{listStyleType: 'none ', padding: 0 }}> {menuItems.map((item, index) => ( <li key ={index} style ={{padding: '10px 0 '}}> <NavLink to ={item.path} style ={{color: 'white ', textDecoration: 'none '}}> {item.title}</NavLink > </li > ))} </ul > </nav > ); } export default Sidebar ;
Add Home, About, and Login pages src/pages/Home.tsx
function Home ( ) { return <h2 > Home Page</h2 > ; } export default Home ;
src/pages/About.tsx
function About ( ) { return <h2 > About Page</h2 > ; } export default About ;
src/pages/Login.tsx
function Login ( ) { return <h2 > Login Page</h2 > ; } export default Login ;
Write the App.tsx src/App.tsx
import {BrowserRouter , Navigate , Route , Routes } from "react-router" ; import MainLayout from "./layouts/MainLayout.tsx" ; import Home from "./pages/Home.tsx" ; import About from "./pages/About.tsx" ; import Login from "./pages/Login.tsx" ; function App ( ) { return ( <> <BrowserRouter > <Routes > <Route path ="/" element ={ <MainLayout /> }> <Route index element ={ <Home /> }/> <Route key ="about" path ="/about" element ={ <About /> }/> </Route > {/*If API call response 401, redirect to login page*/} <Route key ="login" path ="/login" element ={ <Login /> }/> {/* Catch-all route for undefined routes */} <Route key ="*" path ="*" element ={ <Navigate to ="/" replace /> }/> </Routes > </BrowserRouter > </> ) } export default App ;
Running the project
Visiting the project http://localhost:5173/