Routing in React works by mapping URLs to components, allowing users to navigate through different parts of a single-page application without refreshing the entire page.
<aside> 💡 Before setting up routing in a React app, design the overall page layout to organize the main structure, like headers, footers, and navigation bars.
</aside>
Install react-router-dom
npm install react-router-dom
Create Route Components
Layout.jsx
import Footer from "./Footer";
import Navbar from "./Navbar";
import { Outlet } from "react-router-dom";
function Layout(){
return(
<div>
<Navbar/>
{/* Add Dynamic Content Here */}
<div style={{minHeight:'100vh'}}>
<Outlet/>
</div>
<Footer/>
</div>
)
}
export default Layout;
Import Routing → BrowserRouter
Set Up Router in App Component
''
) mapped to the Layout
component.import { Children } from 'react';
import Layout from './Layout';
import {createBrowserRouter,RouterProvider} from 'react-router-dom'
import Register from './Register';
import Login from './Login';
import Home from './Home';
function App(){
// Create Browser Router object
const browserRouter = createBrowserRouter([
{
path:'',
element:<Layout/>,
children:[
{
path:'',
element:<Home/>
},
{
path:'register',
element:<Register/>
},
{
path:'login',
element:<Login/>
}]
},
]);
return (
<RouterProvider router={browserRouter}>
{Children}
</RouterProvider>
)
}
export default App;
Setup links in the Navbar
Link
From react-router-dom
import { Link } from "react-router-dom";
function Navbar(){
return(
<div>
<ul className='nav fs-4 justify-content-end bg-secondary'>
<li className='nav-item'>
<Link to="" className='nav-link text-white'>Home</Link>
</li>
<li className='nav-item'>
<Link to="register" className='nav-link text-white'>Register</Link>
</li>
<li className='nav-item'>
<Link to="login" className='nav-link text-white'>Login</Link>
</li>
</ul>
</div>
)
}
export default Navbar;
https://reactjs-routing.netlify.app/
Install react-router-dom
npm install react-router-dom