In React, if you want to retrieve parameter values from the URL query string, you can use the useLocation hook provided by react-router-dom. The useLocation hook returns a location object representing the current URL. You can use the URLSearchParams API to parse the query string and retrieve specific parameter values.
Here is an example using the useLocation hook and URLSearchParams:
jsximport React from 'react'; import { useLocation } from 'react-router-dom'; function MyComponent() { const location = useLocation(); // Use URLSearchParams to parse the query string const queryParams = new URLSearchParams(location.search); // Retrieve specific parameter values, e.g., 'id' const id = queryParams.get('id'); // Assuming URL is "?id=1234", this returns '1234' return ( <div> <p>ID: {id}</p> </div> ); } export default MyComponent;
This code first imports the useLocation hook from react-router-dom. Inside the component, we call useLocation to obtain the location object for the current URL. We use new URLSearchParams(location.search) to create a new instance of URLSearchParams, which allows us to retrieve specific query parameter values using the get method.
Note that this example assumes your project uses the react-router-dom library for routing. If your project does not use react-router-dom, you may need to use a different approach to retrieve the URL query string.