💻Lecture Notes Of Class 16: useParams and useNavigate in React Router

Rashmi Mishra
0

💻 Lecture Notes Of Class 16

 useParams and useNavigate in React Router

Objective:

  • Understand how to use route parameters to pass dynamic data via URLs.
  • Learn how to navigate programmatically between pages using useNavigate.
  • Build a small product page that dynamically displays product details using URL parameters.
  • Implement navigation buttons to go back and forward.

1. Introduction to React Router Parameters and Navigation

When building web apps with multiple pages, we often need:

  • Dynamic URLs that show different content based on parameters in the URL (e.g., product id).
  • Programmatic navigation to move users between pages, not only through links but also by buttons or events.

React Router provides two useful hooks for these tasks:

  • useParams: To read parameters from the URL.
  • useNavigate: To change the route programmatically.

2. What is useParams?

  • useParams is a React Router hook.
  • It allows you to access the parameters in the URL.
  • Example URL: /products/5 — here, 5 can be a product id passed as a parameter.

How useParams works:

  • In your route definition, you define parameters with a colon : like /products/:id.
  • Inside your component, calling const params = useParams() returns an object with keys equal to the parameter names and values from the URL.

Example:

import React from 'react';

import { useParams } from 'react-router-dom';

 

function ProductPage() {

  const { id } = useParams();  // 'id' corresponds to ':id' in route

 

  return (

    <div>

      <h2>Product Details for Product ID: {id}</h2>

      {/* Here you would fetch product data using this id */}

    </div>

  );

}

 

export default ProductPage;


3. Defining Routes with Parameters

In your main router configuration (usually in App.js or similar):


import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

import ProductPage from './ProductPage'; 

function App() {

  return (

    <Router>

      <Routes>

        <Route path="/products/:id" element={<ProductPage />} />

      </Routes>

    </Router>

  );

}

 

export default App;

  • The :id in the path tells React Router to expect a parameter named id.

4. What is useNavigate?

  • useNavigate is another React Router hook.
  • It returns a function that lets you navigate programmatically between routes.
  • Useful for navigation triggered by events such as button clicks.

Example of useNavigate:

import React from 'react';

import { useNavigate } from 'react-router-dom'; 

function HomePage() {

  const navigate = useNavigate();

 

  const goToProduct = () => {

    navigate('/products/10'); // navigates to product with id 10

  };

 

  return (

    <div>

      <h1>Home Page</h1>

      <button onClick={goToProduct}>View Product 10</button>

    </div>

  );

}

 

export default HomePage;

  • The navigate function changes the URL and renders the new route without reloading the page.

5. Activity: Create a Product Page Showing Details From URL Parameter

Step-by-step:

1.   Setup your React Router with a dynamic route:

<Route path="/products/:id" element={<ProductPage />} />

2.   In ProductPage.js, use useParams to get the product id:

import React from 'react';

import { useParams } from 'react-router-dom'; 

const products = {

  1: { name: 'Phone', price: '$299' },

  2: { name: 'Laptop', price: '$899' },

  3: { name: 'Headphones', price: '$199' }

};

 

function ProductPage() {

  const { id } = useParams();

  const product = products[id];

 

  if (!product) {

    return <h2>Product not found</h2>;

  }

 

  return (

    <div>

      <h2>Product Name: {product.name}</h2>

      <p>Price: {product.price}</p>

    </div>

  );

}

 

export default ProductPage;

3.   Add links or buttons on the home page to navigate to product pages:

import { Link } from 'react-router-dom'; 

function HomePage() {

  return (

    <div>

      <h1>Products</h1>

      <ul>

        <li><Link to="/products/1">Phone</Link></li>

        <li><Link to="/products/2">Laptop</Link></li>

        <li><Link to="/products/3">Headphones</Link></li>

      </ul>

    </div>

  );

}


6. Homework: Add Back and Forward Navigation Buttons Using useNavigate

  • You can use the navigate function with -1 and 1 to go back and forward in history.

Example inside ProductPage.js:

import React from 'react';

import { useParams, useNavigate } from 'react-router-dom';

 

function ProductPage() {

  const { id } = useParams();

  const navigate = useNavigate();

 

  const goBack = () => navigate(-1);  // go back one step

  const goForward = () => navigate(1);  // go forward one step

 

  return (

    <div>

      <h2>Product Details for Product ID: {id}</h2>

      <button onClick={goBack}>Back</button>

      <button onClick={goForward}>Forward</button>

    </div>

  );

}


7. Summary

  • useParams lets you read dynamic segments of the URL, useful for showing different content based on IDs or slugs.
  • useNavigate lets you move users around your app programmatically without links.
  • Combining these hooks allows building dynamic, interactive web pages easily.

8. Additional Tips for Beginners

  • Always check if the parameter exists and is valid before using it to avoid errors.
  • You can pass state or replace options with navigate to control navigation behavior.
  • Practice building small apps with route parameters and navigation buttons to solidify your understanding.
Tags

Post a Comment

0Comments

Post a Comment (0)