In ReactJS, you can retrieve the URL query string using various techniques. Below are commonly used methods:
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
// ...
}
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.
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!