useParams() hook in react

useParams() hook in react

Building Dynamic React Applications with the useParams() Hook: A Beginner's Guide

Introduction

In React Router, URLs represent different states of the application. To access the parameters from the URL, we can use the useParams() hook. In this article, we have explained how to use useParams() hook in React for beginners.

How to use useParams() in React

To use useParams(), you need to have a working React Router setup. Assuming you have a basic React Router setup, you can create a page that displays a single blog post based on its ID in the URL.

First, define your App component with a single route with a path of /blog/:postId. The :postId part of the path is a parameter that can be any string. When this route is matched, React Router will pass the parameter value to the BlogPost component as a prop.

import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import BlogPost from './BlogPost';

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/blog/:postId">
          <BlogPost />
        </Route>
      </Switch>
    </Router>
  );
}

export default App;

Then, create the BlogPost component, import the useParams() hook from React Router and call it to get the postId parameter from the URL. The useParams() hook returns an object with the parameter values as properties. In this case, we destructure the postId property from the returned object. We then use the postId parameter value in the component's JSX to display the title and content of the blog post.

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

function BlogPost() {
  const { postId } = useParams();

  return (
    <div>
      <h1>Blog Post #{postId}</h1>
      <p>This is the content of blog post #{postId}.</p>
    </div>
  );
}

export default BlogPost;

Using Multiple Parameters

You can use multiple parameters in a URL by adding them to the path separated by slashes. For example, if we wanted to add a category parameter to our blog post URL, we could define our route like this:

<Route path="/blog/:category/:postId">
  <BlogPost />
</Route>

And then access the category parameter in our BlogPost component like this:

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

function BlogPost() {
  const { category, postId } = useParams();

  return (
    <div>
      <h1>{category} - Blog Post #{postId}</h1>
      <p>This is the content of blog post #{postId} in the {category} category.</p>
    </div>
  );
}

export default BlogPost;

Conclusion

In conclusion, useParams() is a powerful hook in React Router that allows us to access the parameters from the URL in our React components. It makes it easy to build dynamic applications that respond to changes in the URL. We hope this article has helped you understand how to use useParams() hook in React.