reactjsHow do I retrieve query parameters in ReactJS?
In ReactJS, query parameters can be retrieved by using the URLSearchParams
API. It is a built-in browser API that provides utility methods to work with query strings.
Example code
// Get the current URL
const url = window.location.href;
// Create an object with the URL's query parameters
const params = new URLSearchParams(url.split('?')[1]);
// Get the value of the `name` query parameter
const name = params.get('name');
Output example
name
Code explanation
window.location.href
- The current URLURLSearchParams
- A built-in browser API that provides utility methods to work with query stringsurl.split('?')[1]
- Splits the URL into two parts, the first part being the path and the second part being the query stringparams.get('name')
- Retrieves the value of thename
query parameter
Helpful links
- URLSearchParams - MDN web docs for URLSearchParams
More of Reactjs
- How do I use ReactJS to create an example XLSX file?
- How do I create a zip file using ReactJS?
- How can I use ReactJS and ZeroMQ together to create a distributed application?
- How can I use Git with React.js?
- How do I zip multiple files using ReactJS?
- How do I set the z-index of an element in React.js?
- How can I use ReactJS Zustand to manage state in my application?
- How do I use a timer in ReactJS?
- How do I install Yarn for React.js?
- How can I use Yup with ReactJS?
See more codes...