React Router
React Router
Create React App lacks built-in routing.
Making React Router the go-to choice for navigation.
Install React Route
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.jsHome.jsBlogs.jsContact.jsNotFound.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="">.
Prefer Learning by Watching?
Watch these YouTube tutorials to understand REACT Tutorial visually:
What You'll Learn:
- 📌 Full React Tutorial #21 - The React Router
- 📌 React Router V6 Tutorial - Routes, Redirecting, UseNavigate, UseParams...