React Router
React Router
Create React App lacks built-in routing.
Making React Router the go-to choice for navigation.
Install React Router
To integrate React Router into your project, execute the following command in your terminal from the application's root directory:
Example:
npm install --save-dev react-router-dom
Note: This guide is based on React Router v6.
If you're migrating from an earlier version (v5), ensure you get the latest version by running:
Example:
npm install --save-dev react-router-dom@latest
Project Directory Structure
To build an application with multiple page routes, start by organizing your project files properly.
Inside the src directory, create a pages folder and add the following components:
src/pages/
Layout.js
Home.js
Blogs.js
Contact.js
NotFound.js
Each file will include a simple React component to define its respective page.
Alternative Example: Setting Up React Router
Now, let's configure React Router in our index.js file for navigation
Example:
import ReactDOM from "react-dom/client"; import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; import MainLayout from "./components/MainLayout"; import Dashboard from "./components/Dashboard"; import About from "./components/About"; import Services from "./components/Services"; import NotFound from "./components/NotFound"; export default function App() { return ( <Router> <Route> <Route path="/" element={<MainLayout />}> <Route index element={<Dashboard />} /> <Route path="about" element={<About />} /> <Route path="services" element={<Services />} /> <Route path="*" element={<NotFound />} /> </Route> </Route> </Router> ); } const root = ReactDOM.createRoot(document.getElementById("root")); root.render();
This setup ensures seamless page transitions using React Router
Routing Structure
- The Layout component integrates
</Outlet>
for dynamic route rendering and<Link>
for seamless navigation while preserving history. - Internal paths always utilize
<Link>
instead of<a href="">
.
Previous Next