How to Get URL Parameters in Reactjs Application

    Jul 13, 2023       by Pankaj Kumar
URL-paramers-reactjs.jpg

In ReactJS, you can retrieve the URL query string using various techniques. Below are commonly used methods:

 

 

1. Using the react-router-dom library 

If you are using the react-router-dom library for routing in your React application, you can access the query string parameters using the useLocation hook and the search property.

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

function MyComponent() {
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const value = queryParams.get('key'); // Retrieve the value of a specific query parameter

  // ...
}
 

 

 

2. Using the window.location.search property:

If you are not using react-router-dom or if you simply want a basic approach, you can directly access the window.location.search property to obtain the query string.

function MyComponent() {
  const queryParams = new URLSearchParams(window.location.search);
  const value = queryParams.get('key'); // Retrieve the value of a specific query parameter

  // ...
}
 

 

This method directly accesses the window.location.search property, which contains the query string.

 

3. Using the query-string library:

Another option is to use the query-string library, which provides a simple way to parse and manipulate query strings.

import queryString from 'query-string';

function MyComponent() {
  const parsed = queryString.parse(window.location.search);
  const value = parsed.key; // Retrieve the value of a specific query parameter

  // ...
}
 

 

This method requires installing the query-string library (npm install query-string).

These methods should help you retrieve the URL query string in a ReactJS application. Choose the one that best suits your project's needs and dependencies.

Thanks!


WHAT'S NEW

Find other similar Articles here: