🌐 React Router & Navigation
🌐 What is React Router?
React Router is a standard library for routing in React applications. It lets you:
Navigate between pages (components)
Change the URL in the browser
Handle client-side routing without refreshing the page
🚦 Why Use React Router?
✅ Create multi-page experiences
✅ Link between views (e.g., Home → About → Contact)
✅ Support deep linking (e.g., /products/123)
✅ Easily manage navigation programmatically
🧱 Basic Setup
1. Install React Router
bash
Copy
Edit
npm install react-router-dom
2. Create Routes
Here’s a simple example:
jsx
Copy
Edit
// App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
function App() {
return (
<Router>
<nav>
<Link to="/">Home</Link> |
<Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
export default App;
3. Create Page Components
jsx
Copy
Edit
// pages/Home.js
const Home = () => <h2>Welcome to the Home Page</h2>;
export default Home;
// pages/About.js
const About = () => <h2>About This App</h2>;
export default About;
🔄 Navigation Methods
🧭 Using Links
jsx
Copy
Edit
<Link to="/about">Go to About</Link>
🚀 Navigate Programmatically
jsx
Copy
Edit
import { useNavigate } from 'react-router-dom';
const MyComponent = () => {
const navigate = useNavigate();
const handleClick = () => navigate('/about');
return <button onClick={handleClick}>Go to About</button>;
};
🧩 Route Parameters
You can pass dynamic data in the URL:
jsx
Copy
Edit
<Route path="/user/:id" element={<UserPage />} />
jsx
Copy
Edit
// UserPage.js
import { useParams } from 'react-router-dom';
const UserPage = () => {
const { id } = useParams();
return <div>User ID: {id}</div>;
};
🛑 404 Not Found Page
Catch unmatched routes:
jsx
Copy
Edit
<Route path="*" element={<h2>404 Not Found</h2>} />
✅ Summary
React Router enables SPA navigation without reloads
Use <Routes> and <Route> to define paths
Use <Link> or useNavigate() to move between views
Supports dynamic routes and nested routes
Always wrap routing logic inside <BrowserRouter>
Learn React JS Course in Hyderabad
Read More
Best Practices for Managing Forms in React
Integrating React with Yup for Validation
Building a Dynamic Form Component
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment