
Router in ReactJS
✅ React Router in ReactJS
React Router is a standard library for handling routing in ReactJS applications. It enables the creation of single-page applications (SPAs) with multiple views, allowing users to navigate between pages without refreshing the browser.
📌 Why Use React Router?
Client-Side Routing → Navigates between pages without reloading.
Component-Based Navigation → Routes are linked to components.
Dynamic Routing → Supports URL parameters and query strings.
Browser History Management → Enables back and forward navigation.
📌 Installation
First, install React Router using npm or yarn:
npm install react-router-dom<Router> <h1>Welcome to the Home Page<h1>About Us Page<h1>Contact Us Page<h1>404 - Page Not Found<h1>Product Details for Product ID: {id}<div> <div> <Router> <Routes> <Route path="/" element={isLoggedIn ? <h1>Welcome</h1> : <Navigate to="/login" />} /> <Route path="/login" element={<h1>Login Page</h1>} /> </Routes> </Router> );};export default App;
🛠 Explanation:
<Navigate to="/path" />
→ Redirects users to the specified path.
✅ Final Thoughts
React Router makes SPA navigation easy and efficient.
Use
<Link>
for navigating without page reloads.Use
useParams()
for accessing dynamic route parameters.Use
useNavigate()
for programmatic navigation.Handle 404 errors using a wildcard
*
route.