Open In App

How to Get Parameter Value from Query String in ReactJS?

Last Updated : 03 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In React query parameter are a way to pass the data as props from the url to react components. Getting parameter value from query string helps to render the dynamic data depending on the query.

Approach

To get the parameter value from query string in React we will be using the query-string packge. We will get the url using window.location and parse the string with the help of queryString.parse method.

 For example, the query string is ?site=gfg&subject=react then after parsing object will be:

{
 site:"gfg",
 subject:"react"
}

Steps to Create React App

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. folder name, move to it using the following command:

cd foldername

Step 3: Install the required module

npm install query-string 

Project Structure:

It will look like the following

The updated dependencies in the package.json file are:

  "dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"query-string": "^9.1.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Example: This example access the query parameters by parsing the URL’s query string using queryString.parse() and updating the component’s state with the retrieved values.

// Filename: App.js

import React, { useState } from "react";
import queryString from "query-string";

const App = () => {
	// Using useState hook for managing state
	const [site, setSite] = useState("unknown");
	const [subject, setSubject] = useState("i dont know");

	const handleQueryString = () => {
		// Parsing the query string from the window.location.search
		const queries = queryString.parse(window.location.search);
		console.log(queries);
		setSite(queries.site || "unknown");
		setSubject(queries.subject || "i dont know");
	};

	return (
		<div style={{ margin: 200 }}>
			<p> WebSite: {site} </p>
			<p> Subject: {subject} </p>

			<button onClick={handleQueryString} className="btn btn-primary">
				click me
			</button>
		</div>
	);
};

export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

output---get-parameter-value-from-query-string




Next Article

Similar Reads