React Router helps us build single-page web applications (SPAs) with navigation between different views without reloading the page. Imagine React Router as the GPS for your React application, smoothly guiding users through your web app without ever stopping for directions.
React Router provides smooth and instant transitions between pages (or components), giving users a faster and more intuitive navigation experience compared to traditional page reloads.
Create a new React app:
npx create-react-app router_example
cd router_example
npm install react-router-dom
npm start
Your project structure:
router_example/
├── node_modules/
├── public/
│ ├── favicon.png
│ └── index.html
└── src/
├── App.js
├── index.js
└── components/
├── Home.js
├── About.js
└── Dashboard.js
└── Profile.js
// src/components/Home.js
export default function Home() {
return <h2>Home Page</h2>;
}
// src/components/About.js
export default function About() {
return <h2>About Page</h2>;
}
// src/components/Dashboard.js
import { Outlet, Link } from 'react-router-dom';
export default function Dashboard() {
return (
<div>
<h2>Dashboard</h2>
<nav>
<Link to="profile">Profile</Link>
</nav>
<Outlet />
</div>
);
}
// src/components/Dashboard/Profile.js
import { useParams } from 'react-router-dom';
export default function Profile() {
const { username } = useParams();
return <h3>Profile: {username}</h3>;
}
// src/App.js
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Dashboard from './components/Dashboard';
import Profile from './components/Dashboard/Profile';
export default function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> |
<Link to="/about">About</Link> |
<Link to="/dashboard">Dashboard</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/dashboard" element={<Dashboard />}>
<Route path="profile/:username" element={<Profile />} />
</Route>
</Routes>
</BrowserRouter>
);
}
Protected routes are components that are accessible only to authenticated users. Imagine protected routes as locked rooms in your app; users need a key (authentication) to enter.
// src/components/ProtectedRoute.js
import { Navigate } from 'react-router-dom';
export default function ProtectedRoute({ children, isAuthenticated }) {
return isAuthenticated ? children : <Navigate to="/" />;
}
Implement protected routes in App.js:
// Updated App.js
import ProtectedRoute from './components/ProtectedRoute';
// Inside <Routes>
<Route path="/dashboard" element={
<ProtectedRoute isAuthenticated={true}>
<Dashboard />
</ProtectedRoute>
}>
<Route path="profile/:username" element={<Profile />} />
</Route>
Properly structuring routes and handling authentication securely ensures a robust, maintainable, and secure application. React Router documentation (https://reactrouter.com) provides comprehensive resources for deeper exploration.
Happy coding!