Hi 👋,
Welcome To Infinitbility! ❤️
To get the query string value in react js, just use window.location.search
it will return the query string and you can use it as you want.
For now, we are taking the query string using window.location.search
and converting its parameter into objects.
const parseParams = (querystring) => {
// parse query string
const params = new URLSearchParams(querystring);
const obj = {};
// iterate over all keys
for (const key of params.keys()) {
if (params.getAll(key).length > 1) {
obj[key] = params.getAll(key);
} else {
obj[key] = params.get(key);
}
}
return obj;
};
// 👇️ {"name":"infinitbility"}
console.log(parseParams('?name=infinitbility'));
Today, I’m going to show you How do I get query string value in react js, as above mentioned here, I’m going to use the window.location.search
and convert it into an object so we can use it when we want.
Let’s start today’s tutorial how do you get query string value in react js?
In this example, we will do
- create a sample URL parse function that can convert query string
- get query string in
useEffect
usingwindow.location.search
- print created object on a page
Let’s write code…
import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [queryParam, setQueryParam] = useState({});
const parseParams = (querystring) => {
// parse query string
const params = new URLSearchParams(querystring);
const obj = {};
// iterate over all keys
for (const key of params.keys()) {
if (params.getAll(key).length > 1) {
obj[key] = params.getAll(key);
} else {
obj[key] = params.get(key);
}
}
return obj;
};
useEffect(() => {
let params = parseParams(window.location.search);
setQueryParam(params)
console.log(params);
}, []);
return (
<div className="App">
<h1>{JSON.stringify(queryParam)}</h1>
</div>
);
}
As mentioned above, we are taken the example of a sample query string URL, created a function that can convert URL params to objects, and printed output on a screen.
Let’s check the output.
I hope it’s help you, All the best 👍.