In React, you can get parameter values from a query string using several methods. Here are some common approaches:
1. Using URLSearchParams
The URLSearchParams
API is a modern and straightforward way to parse query strings in JavaScript.
Example:
import { useEffect } from "react";
const MyComponent = () => {
useEffect(() => {
const queryParams = new URLSearchParams(window.location.search);
const paramValue = queryParams.get("paramName");
console.log("Parameter value:", paramValue);
}, []);
return <div>Check the console for the parameter value.</div>;
};
export default MyComponent;
window.location.search
: Returns the query string (e.g.,?paramName=value
).queryParams.get('paramName')
: Extracts the value of the parameter namedparamName
.
2. Using React Router’s useSearchParams
(React Router v6 and above)
If you’re using React Router, you can use the useSearchParams
hook to work with query strings.
Example:
import { useSearchParams } from "react-router-dom";
const MyComponent = () => {
const [searchParams] = useSearchParams();
const paramValue = searchParams.get("paramName");
return <div>Parameter value: {paramValue}</div>;
};
export default MyComponent;
searchParams.get('paramName')
: Retrieves the value for the specified parameter.
3. Using React Router’s useLocation
(Older Versions or Flexibility with Parsing)
If you’re using an older version of React Router (v5 or below) or need more manual parsing:
Example:
import { useLocation } from "react-router-dom";
const MyComponent = () => {
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const paramValue = queryParams.get("paramName");
return <div>Parameter value: {paramValue}</div>;
};
export default MyComponent;
location.search
: Provides the query string (e.g.,?paramName=value
).
4. Manually Parsing the Query String
If you want to manually parse the query string without using URLSearchParams
:
Example:
const MyComponent = () => {
const getQueryParam = (paramName) => {
const query = window.location.search.substring(1);
const params = query.split("&");
for (let param of params) {
const [key, value] = param.split("=");
if (key === paramName) return decodeURIComponent(value);
}
return null;
};
const paramValue = getQueryParam("paramName");
return <div>Parameter value: {paramValue}</div>;
};
export default MyComponent;
When to Use Each Method
- Modern Apps: Prefer
URLSearchParams
or React Router’suseSearchParams
. - React Router Integration: Use
useSearchParams
(v6+) oruseLocation
(v5 and below). - Manual Parsing: Use manual parsing if you have unique requirements or are not using React Router.
These approaches will help you extract query string parameters in any React project!