@ryan.murray
In React, you can access the query parameters of a URL using the URLSearchParams
API provided by the browser. Here's how you can do it:
1
|
import { useLocation } from 'react-router-dom'; |
Note: Make sure you have installed the react-router-dom
package if you haven't already.
1 2 3 4 5 6 7 8 9 10 |
const MyComponent = () => { const location = useLocation(); const queryParams = new URLSearchParams(location.search); // Access specific query parameter values const paramName = queryParams.get('paramName'); // Use the parameter values in your component // ... }; |
Note: The useLocation
hook provided by React Router returns a location
object that contains the current URL's information, including the query parameters.
Now, you can access specific query parameter values by calling the get
method of the URLSearchParams
object initialization queryParams.get('paramName')
, where 'paramName' is the name of the query parameter you want to access.
Using the above approach, you can easily retrieve and use the query parameters in your React components.