How to access URL path using useParams hook in React js

In my previous posts, we studied various hooks that come with the React package which enable us to perform different functions within our app. Today, we’ll explore the useParams hook that comes with React-Router-dom package and allows us to access the URL parameters. For example, if you want to access the id for a particular URL, then you will have to make use of the useParams hook.

In this tutorial, we will create a simple app in which there is a list of products, and clicking on an individual product will redirect the user to the product detail page. In order to access the product detail page, we will make use of the useParams hook.

Let’s start by creating a new React app. Type in the following command on our command line:

npx create-react-app useparams-example-app

Now, we navigate to our app and clear out some unnecessary files like logo.svg. We can also remove the commented out code to make our app look neat and clean.

Now, we need to install the react-router-dom package in order to be able to access different routes and make use of the useParams hook:

npm i react-router-dom

We now navigate to the App.js file of our app and write some basic code to be displayed on the Home page of our app. We also need to import BrowserRouter, Switch, Route, Link, and useParams objects from react-router-dom to be able to access the navigation properties of this package.

After the imports and rendering the home page of our app at the default path of "/", our App.js file will look like the following:

import React from 'react'
import './App.css';
import { BrowserRouter as Router,Switch , Route, Link, useParams} from 'react-router-dom';


function App() {

  return (
    <BrowserRouter>
<div className="App">
   <h1>React Router useParams Hook Demo</h1>
   <div className="navbar">
   <Link to="/">Home</Link>
   </div>
  
   <Switch>
     <Route exact path="/">
       <h2><p>Welcome to the Home Component</p></h2>
     </Route>
     
    </div>
    </BrowserRouter>
    
  );
}

export default App;

Notice that we have to wrap the entire component in the BrowserRouter component and the Link method will create a hyperlink to access a particular component.

We will also create an “About us” page to make things more clear. For this, we will have to create an About.js file in the src directory of our project. The code for the About.js file is mentioned below:

import React from 'react'

export const About = () => {
    return (
        <div>
            <h2>About Us Component</h2> 

        </div>
    )
}

Now, let’s write some code related to the useParams hook. Here, we have a list of products that we want to list on a “Products” page in our app. We will first include the products object in the App.js as follows:

const products = {
    "air-jordan-3-valor-blue": {
      name: "VALOUR BLUE",
      img:
        "https://secure-images.nike.com/is/image/DotCom/CT8532_104_A_PREM?$SNKRS_COVER_WD$&align=0,1"
    },
    "jordan-mars-270-london": {
      name: "JORDAN MARS 270 LONDON",
      img:
        "https://secure-images.nike.com/is/image/DotCom/CV3042_001_A_PREM?$SNKRS_COVER_WD$&align=0,1"
    },
    "air-jordan-1-zoom-racer-blue": {
      name: "RACER BLUE",
      img:
        "https://secure-images.nike.com/is/image/DotCom/CK6637_104_A_PREM?$SNKRS_COVER_WD$&align=0,1"
    }
  };

Now, we will create a link to the “Products” page where we will list all the above products nicely:

import React from 'react'
import './App.css';
import { BrowserRouter as Router,Redirect, Switch ,Route,Link} from 'react-router-dom';
import {ProductsPage} from './components/ProductsPage'
import {About } from './components/About'

function App() {

  const products = {
    "air-jordan-3-valor-blue": {
      name: "VALOUR BLUE",
      img:
        "https://secure-images.nike.com/is/image/DotCom/CT8532_104_A_PREM?$SNKRS_COVER_WD$&align=0,1"
    },
    "jordan-mars-270-london": {
      name: "JORDAN MARS 270 LONDON",
      img:
        "https://secure-images.nike.com/is/image/DotCom/CV3042_001_A_PREM?$SNKRS_COVER_WD$&align=0,1"
    },
    "air-jordan-1-zoom-racer-blue": {
      name: "RACER BLUE",
      img:
        "https://secure-images.nike.com/is/image/DotCom/CK6637_104_A_PREM?$SNKRS_COVER_WD$&align=0,1"
    }
  };

  return (
    <BrowserRouter>
<div className="App">
   <h1>React Router useParams Hook Demo</h1>
   <div className="navbar">
   <Link to="/">Home</Link>
   <Link to="/products">Products</Link>
   <Link to="/about">About</Link>
   </div>
  
   
   <Switch>
     <Route exact path="/">
       <h2><p>Welcome to the Home Component</p></h2>
       
     </Route>
     <Route path="/products">
    <ProductsPage products={products}/>
     </Route>
     <Route path="/about">
       <About />
     </Route>
   </Switch>
    </div>
    </BrowserRouter>
    
  );
}

export default App;

Notice that we passed the products object as a prop to the ProductsPage component so that we can display it there.

Now, create a ProductsPage component and display the products:

import React from 'react'
import { Link, Switch, Route } from 'react-router-dom'


export const ProductsPage = ({products}) => {
 
    return (
       
        <div className="product-box">

        <h2 className="title"> Products Component</h2>
        <div className="box">
        {Object.entries(products).map(([id, {name,img}]) => (
                <li key={id}>
                    <Link to={`/product/${id}`}>
                        <h2 className="product-name">{name}</h2>
                        <img src={img} alt={name}/>
                    </Link>
                </li>
            ))} 
        </div>
            

        </div>
    )
}

We made use of the JavaScript map method to display the list of products.

Notice that the name of each product is a link that will navigate to the detail page of each product:

import React from 'react'
import { useParams } from 'react-router'

export const Product = ({products}) => {
    let {id} = useParams();
    const product = products[slug]

    const {name,img} = product;
    {console.log(id)}
   
    return (
        <div>
           <h2>This is the Product Detail component</h2> 
            <h2>{slug}</h2>
            <h3>Brand: {name}</h3>
            <img src={img}  alt={name}/>
        </div>
    )
}

In the Product component, we will use the useParams hook to extract the id from the URL for each product.

You may be wondering from where the id is passed to the Product component. It was passed from App.js, where we defined the Route for the Product component by specifying the colon symbol, i.e., <path="/product/:id">:

import React from 'react'
import './App.css';
import { BrowserRouter as Router,Redirect, Switch ,Route,Link,useParams} from 'react-router-dom';
import {ProductsPage} from './components/ProductsPage'
import {About } from './components/About;
import {Product} from './components/Product'

function App() {

  const products = {
    "air-jordan-3-valor-blue": {
      name: "VALOUR BLUE",
      img:
        "https://secure-images.nike.com/is/image/DotCom/CT8532_104_A_PREM?$SNKRS_COVER_WD$&align=0,1"
    },
    "jordan-mars-270-london": {
      name: "JORDAN MARS 270 LONDON",
      img:
        "https://secure-images.nike.com/is/image/DotCom/CV3042_001_A_PREM?$SNKRS_COVER_WD$&align=0,1"
    },
    "air-jordan-1-zoom-racer-blue": {
      name: "RACER BLUE",
      img:
        "https://secure-images.nike.com/is/image/DotCom/CK6637_104_A_PREM?$SNKRS_COVER_WD$&align=0,1"
    }
  };

  return (
    <BrowserRouter>
<div className="App">
   <h1>React Router useParams Hook Demo</h1>
   <div className="navbar">
   <Link to="/">Home</Link>
   <Link to="/topics">Topics</Link>
   <Link to="/about">About</Link>
   </div>
  
   
   <Switch>
     <Route exact path="/">
       <h2><p>Welcome to the Home Component</p></h2>
       
     </Route>
     <Route path="/products">
    <ProductsPage products={products}/>
     </Route>
     <Route path="/about">
       <About />
     </Route>
     <Route path="/product/:id"><Product products={products}/></Route>
   </Switch>
    </div>
    </BrowserRouter>
    
  );
}

export default App;

So, in this manner, we can display all the products and also output the ID for each product with the use of the useParams hook.

Free Resources