get search params from url react router 5

How to Get Search Params from URL using React Router 5

Have you ever needed to retrieve search parameters from the URL in your React application? React Router 5 provides an easy way to do so using the useLocation hook from the react-router-dom package.

Step 1: Import the necessary components

First, make sure you have both react-router-dom and highlight.js installed in your project:

npm install react-router-dom highlight.js

Then, import the components you'll need in your React component:

import React from 'react';
import { useLocation } from 'react-router-dom';
import hljs from 'highlight.js';

Step 2: Retrieve the search parameters

Next, use the useLocation hook to retrieve the search parameters from the URL:

function MyComponent() {
  const location = useLocation();
  const params = new URLSearchParams(location.search);
  
  // do something with the params...
  
  return (
    <div>
      <p>Search parameters: {params.toString()}</p>
    </div>
  );
}

export default MyComponent;

The location.search property contains the search parameters as a string, which we can pass to the URLSearchParams constructor to create a new object we can work with.

Bonus: Using Multiple Search Parameters

If you have multiple search parameters in the URL, you can use the get() method of the URLSearchParams object to retrieve a specific parameter:

function MyComponent() {
  const location = useLocation();
  const params = new URLSearchParams(location.search);
  
  const searchTerm = params.get('q');
  const pageNumber = params.get('page');
  
  // do something with the search term and page number...
  
  return (
    <div>
      <p>Search term: {searchTerm}</p>
      <p>Page number: {pageNumber}</p>
    </div>
  );
}

export default MyComponent;

In this example, we're retrieving two search parameters - q and page - and using their values in our component.

Conclusion

Retrieving search parameters from the URL in your React application using React Router 5 is simple and straightforward. By using the useLocation hook and the URLSearchParams object, you can easily access and use this data in your components.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe