React Router v6: Routing Basics
When building single-page applications (SPAs) with React, navigating between views without reloading the page is essential. React Router v6 is the latest version of the popular routing library that simplifies navigation and route management in React applications.
π What is React Router?
React Router enables dynamic routing in a React app. It allows you to define routes for different components and navigate between them without refreshing the browser.
React Router v6 introduces a cleaner syntax, better performance, and nested route support.
π¦ Installation
To get started, install React Router:
npm install react-router-dom
Make sure you have React 16.8+ installed for compatibility.
πΊ️ Defining Routes
Set up routing in your App.js or root component using <BrowserRouter>, <Routes>, and <Route>:
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
<BrowserRouter>: Wraps the app and enables routing using the browser’s history API.
<Routes>: Replaces Switch from v5; it matches only one route at a time.
<Route>: Maps a path to a component using the element prop.
π Navigating Between Pages
Use the <Link> component instead of <a> for navigation without full-page reloads:
import { Link } from 'react-router-dom';
<Link to="/">Home</Link>
<Link to="/about">About</Link>
π Nested Routes (v6 Feature)
React Router v6 supports nested routes natively
<Route path="/dashboard" element={<Dashboard />}>
<Roue path="settings" element={<Settings />} />
</Route>
Within Dashboard, use <Outlet /> to render child routes.
❌ 404 Not Found Route
Add a catch-all route at the end:
<Route path="*" element={<NotFound />} />
π Conclusion
React Router v6 simplifies client-side routing in React apps with its clean, modern syntax. With features like nested routing, route matching, and <Outlet>, managing navigation becomes more intuitive and maintainable.
Whether you're building a blog, admin dashboard, or e-commerce site, React Router v6 provides the tools you need for seamless navigation.
Let me know if you'd like an extended version with protected routes or dynamic routing examples!
Learn MERN Stack Training Course
Conditional Rendering and Ternary Operators
Rendering Lists with the map() Function
Handling Events in React Components
Lifting State Up and Prop Drilling
Visit Our Quality Thought Training Institute
Comments
Post a Comment