📄Assignments Of Class 16: useParams and useNavigate in React Router
Assignment 1: Create a User Profile
Page Using useParams
Task:
Create a route /users/:username that shows a user profile page with the
username extracted from the URL.
Solution:
jsx
CopyEdit
// App.js
import { BrowserRouter as Router, Routes,
Route } from 'react-router-dom';
import UserProfile from './UserProfile';
function App() {
return (
<Router>
<Routes>
<Route path="/users/:username"
element={<UserProfile />} />
</Routes>
</Router>
);
}
export default App;
// UserProfile.js
import React from 'react';
import { useParams } from 'react-router-dom';
function UserProfile() {
const { username } = useParams();
return (
<div>
<h2>Welcome to {username}'s Profile</h2>
<p>This page shows details about {username}.</p>
</div>
);
}
export default UserProfile;
Assignment 2: Navigate to Product
Page with Button Click
Task:
On the home page, create a button that navigates to /products/5
programmatically using useNavigate.
Solution:
jsx
CopyEdit
// HomePage.js
import React from 'react';
import { useNavigate } from 'react-router-dom';
function HomePage() {
const navigate = useNavigate();
const goToProduct = () => {
navigate('/products/5');
};
return (
<div>
<h1>Home</h1>
<button onClick={goToProduct}>Go to Product 5</button>
</div>
);
}
export default HomePage;
Assignment 3: Display Product
Details Based on id Parameter
Task:
Create a product details page using /products/:id where product info is
displayed based on the id in the URL.
Solution:
jsx
CopyEdit
// products.js (mock data)
export const products = {
1: { name: 'Laptop', price: '$1000' },
2: { name: 'Tablet', price: '$600' },
3: { name: 'Smartphone', price: '$400' }
};
// ProductPage.js
import React from 'react';
import { useParams } from 'react-router-dom';
import { products } from './products';
function ProductPage() {
const { id } = useParams();
const product = products[id];
if (!product) {
return <h2>Product not found</h2>;
}
return (
<div>
<h2>{product.name}</h2>
<p>Price: {product.price}</p>
</div>
);
}
export default ProductPage;
Assignment 4: Add Navigation Buttons
for Back and Forward
Task:
In the product page, add Back and Forward buttons that navigate
through the browser history.
Solution:
jsx
CopyEdit
import React from 'react';
import { useNavigate, useParams } from
'react-router-dom';
function ProductPage() {
const { id } = useParams();
const navigate = useNavigate();
return (
<div>
<h2>Product ID: {id}</h2>
<button onClick={() => navigate(-1)}>Back</button>
<button onClick={() => navigate(1)}>Forward</button>
</div>
);
}
export default ProductPage;
Assignment 5: Create a List of
Products with Links
Task:
Create a homepage that lists products with clickable links navigating to their
product detail pages using <Link>.
Solution:
jsx
CopyEdit
import React from 'react';
import { Link } from 'react-router-dom';
const products = [
{ id: 1, name: 'Laptop' },
{ id: 2, name: 'Tablet' },
{ id: 3, name: 'Smartphone' },
];
function HomePage() {
return (
<div>
<h1>Product List</h1>
<ul>
{products.map(p => (
<li key={p.id}>
<Link to={`/products/${p.id}`}>{p.name}</Link>
</li>
))}
</ul>
</div>
);
}
export default HomePage;
Assignment 6: Redirect to Home if
Product Not Found
Task:
If a product with the given id does not exist, automatically redirect the user
back to the home page using useNavigate.
Solution:
jsx
CopyEdit
import React, { useEffect } from 'react';
import { useParams, useNavigate } from
'react-router-dom';
const products = {
1: { name: 'Laptop' },
2: { name: 'Tablet' },
};
function ProductPage() {
const { id } = useParams();
const navigate = useNavigate();
useEffect(() => {
if (!products[id]) {
navigate('/', { replace: true });
}
}, [id, navigate]);
const product = products[id];
if (!product) return null;
return (
<div>
<h2>{product.name}</h2>
</div>
);
}
export default ProductPage;
Assignment 7: Programmatic
Navigation with State
Task:
Navigate to a product page and pass additional state (e.g., fromHome: true)
using useNavigate.
Solution:
jsx
CopyEdit
// HomePage.js
import React from 'react';
import { useNavigate } from 'react-router-dom';
function HomePage() {
const navigate = useNavigate();
const goToProduct = () => {
navigate('/products/1', { state: { fromHome: true } });
};
return <button onClick={goToProduct}>Go to Product 1</button>;
}
export default HomePage;
// ProductPage.js
import React from 'react';
import { useLocation, useParams } from
'react-router-dom';
function ProductPage() {
const { id } = useParams();
const location = useLocation();
return (
<div>
<h2>Product ID: {id}</h2>
{location.state?.fromHome && <p>You came here from the
Home page!</p>}
</div>
);
}
export default ProductPage;
Assignment 8: Create a Nested Route
with Parameter
Task:
Create a route /products/:id/reviews that shows reviews for a specific product.
Solution:
jsx
CopyEdit
// App.js
import { BrowserRouter as Router, Routes,
Route } from 'react-router-dom';
import ProductPage from './ProductPage';
import Reviews from './Reviews';
function App() {
return (
<Router>
<Routes>
<Route path="products/:id"
element={<ProductPage />}>
<Route path="reviews" element={<Reviews
/>} />
</Route>
</Routes>
</Router>
);
}
export default App;
// ProductPage.js
import React from 'react';
import { Outlet, useParams, Link } from
'react-router-dom';
function ProductPage() {
const { id } = useParams();
return (
<div>
<h2>Product {id} Details</h2>
<Link to="reviews">See Reviews</Link>
<Outlet />
</div>
);
}
export default ProductPage;
// Reviews.js
import React from 'react';
function Reviews() {
return <div><h3>Reviews go here...</h3></div>;
}
export default Reviews;
Assignment 9: Use navigate(-1) to
Implement a Custom Back Button
Task:
Create a "Go Back" button on any page that navigates the user to the
previous page.
Solution:
jsx
CopyEdit
import React from 'react';
import { useNavigate } from 'react-router-dom';
function BackButton() {
const navigate = useNavigate();
return <button onClick={() => navigate(-1)}>Go Back</button>;
}
export default BackButton;
Assignment 10: Protect a Route Using
useNavigate
Task:
Redirect users to /login if a condition (like user not logged in) is false when
accessing /dashboard.
Solution:
jsx
CopyEdit
import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
function Dashboard() {
const navigate = useNavigate();
const isLoggedIn = false; // assume user is not logged in
useEffect(() => {
if (!isLoggedIn) {
navigate('/login', { replace: true });
}
}, [isLoggedIn, navigate]);
if (!isLoggedIn) return null;
return <h2>Welcome to Dashboard</h2>;
}
export default Dashboard;
Summary
These
assignments cover:
- Extracting URL parameters with useParams
- Programmatic navigation with useNavigate
- Creating dynamic routes and
nested routes
- Handling redirects and
navigation with state
- Adding back and forward
navigation buttons
