DEV Community

Cover image for React Router: A Beginners guide to useParams hook.
Stanlisberg
Stanlisberg

Posted on

React Router: A Beginners guide to useParams hook.

In this guide, we will be unravelling the complexity in one of React Router's hook called: useParams. We will learn about its implementation and functionality. Ride along with me.

Prerequisite
You should have the following to follow along with this guide:

  • A very basic knowledge of react.
  • A code editor.
  • A browser.

You might be wondering; why is it necessary to use useParams? I will gladly explain the reason to you. When it involves Routing, there are some Routes that have dynamic parameters attached to their path string and the useParams hooks provides an avenue for us to access those dynamic parameters in the Route.

What is useParams?

useParams is a hook that allows you to have access to dynamic parameters in the URL(Uniform Resource Locator).

Setting up React Router
Using npm
npm install react-router-dom

Because useParams hook is based off React Router, we need to import BrowserRouter, Routes and Route from react-router-dom.

Routing

From the image above, we have set up React Router.

We are going to demonstrate the implementation of useParams with a mini project. In this project, we will be working with two (2) components namely: CardComponent and CardInfo.
Firstly, we will structure our App component by declaring an array of objects that holds our card data and also configure our Routes.

App Component

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import CardComponent from "./components/CardComponent";

function App() {
  const cardData = [
    {
      name: "HTML",
      title: "Markup Language",
      description:
        "HTML is a markup language that describe the structure of web pages"
    },
    {
      name: "CSS",
      title: "Styling Language",
      description:
        "CSS is a Style sheet language which is used to describe the look and formatting of a document written in markup language."
    },
    {
      name: "JAVASCRIPT",
      title: "Programming Language",
      Description:
        "Javascript is a programming language that adds interactivity to web pages"
    },
    {
      name: "REACT",
      title: "Javascript Library",
      description:
        "React is a JavaScript-based UI development library for building user interfaces based on components."
    }
  ];

  return (
    <div className="App">
      <Router>
        <Routes>
          <Route path="/" element= <CardComponent data= {cardData} /> />
        </Routes>
      </Router>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

From the code snippet above, we declared an array of objects that hold some datas, passed it as a prop to CardComponent and also configured our Routes by specifying a path to our CardComponent.

<Route path="/" element=<CardComponent data={cardData} />

The path="/" is targeted to display CardComponent's content on the index(home) page.

CardComponent

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

function CardComponent({ data }) {
  return (
    <>
      <section className="wrapper">
        <div className="container">
          {data.map((item, index) => (
            <div className="card" key={index}>
              <h3>{item.name}</h3>
              <p>{item.title}</p>
              <Link to={`/info/${item.name}/`}>View Discription</Link>
            </div>
          ))}
        </div>
      </section>
    </>
  );
}
export default CardComponent;
Enter fullscreen mode Exit fullscreen mode

From the code snippet above, we imported Link from react-router-dom. Link is an element that lets the user navigate to another page by clicking on it.
Recall that we passed our cardData as a prop in the App component child's component which in this case is CardComponent. Now we are Destructuring that data to have access to it and mapping its content in a div element with a class of card.

See the output below.

mapped data

Implementing useParams (i)
Let's go back to our App component and add some few things.

useParams
The image above shows that we imported the CardInfo component and rendered it as a child component in App component while passing the cardData array as prop. I know what you are thinking; "Where did CardInfo component appeared from?" Don't worry, we are on the right track, I purposely did that so as to explain how we can set up our Route for useParams.

<Route path="/info/:name" element=<CardInfo data={cardData} /> />

If we take a good look at the code above, the path string is directed to /info/:name. What this means is that, the colon : before name is an indicator that informs React that this is a dynamic Route and that name is now a property of useParams. This name can be anything but it must match which that of the useParams object.

Also, from our card component:

<Link to={/info/${item.name}/}>View Discription</Link>

The code specifies that Link will navigate to CardInfo component.

Note: In our App component, you must understand that the parameter after the : which is name, is now a reference to item.name from our Link path. ie, the Link will navigate to /info/:name.

Lets introduce our CardInfo component and put all the pieces together. Shall we?

Implementing useParams (ii)
CardInfo

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

function CardInfo({ data }) {
  const { name } = useParams();

  return (
    <>
      <section className="card-wrapper">
        <div className="card-container">
          {data
            .filter((item) => item.name === name)
            .map((item, index) => (
              <div className="card-info" key={index}>
                <h2>{item.name}</h2>
                <p>{item.description}</p>
              </div>
            ))}
        </div>
      </section>
    </>
  );
}

export default CardInfo;
Enter fullscreen mode Exit fullscreen mode

We have imported the useParams hook from react-router-dom and accessed its property by using the Destructuring concept.

const { name } = useParams();

Recall that the path string to navigate to CardInfo component is /info/:name in our App component and we have gained access to the :name parameter by using destructuring. Now, name is an object of useParams in this case.

Note: nameas an object of useParams must match with that of the parameter name specified in the path string of the route definition which in this case is :name else you will encounter an error. Basically, you can name the parameter anything you want, but it is ideal to match it with one of the key in your data object so thereโ€™s no confusion. Also, from our Link, ${item.name} is a reference to the name object of useParams.

We have filtered our data to return the name value that will be clicked from our Link and also mapped the output from the filtered data to return the name and description value of our desired card. Check the output below.

Functionality

Click the view description button and see the magic.

output of navigated route

if you take a look at that arrow from the image, you will see that we have successfully navigated to/info/HTML because we clicked the view description button of the HTML card. We have achieved this with the help of the useParams hook.

Conclusion

In this guide, we have discussed how to use the useParams hook in React. We have also streamlined the implementation and functionality of the hook by using a mini project to explain how
you can use this hook to navigate to dynamic URL in our web applications. I hope you learnt something new from this article. Goodluck in our career!

Top comments (0)