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.
1const parseParams = (querystring) => {2 // parse query string3 const params = new URLSearchParams(querystring);45 const obj = {};67 // iterate over all keys8 for (const key of params.keys()) {9 if (params.getAll(key).length > 1) {10 obj[key] = params.getAll(key);11 } else {12 obj[key] = params.get(key);13 }14 }1516 return obj;17 };18// 👇️ {"name":"infinitbility"}19console.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…
1import React, { useState, useEffect } from "react";2import "./styles.css";3export default function App() {4 const [queryParam, setQueryParam] = useState({});56 const parseParams = (querystring) => {7 // parse query string8 const params = new URLSearchParams(querystring);910 const obj = {};1112 // iterate over all keys13 for (const key of params.keys()) {14 if (params.getAll(key).length > 1) {15 obj[key] = params.getAll(key);16 } else {17 obj[key] = params.get(key);18 }19 }2021 return obj;22 };2324 useEffect(() => {25 let params = parseParams(window.location.search);26 setQueryParam(params)27 console.log(params);28 }, []);29 return (30 <div className="App">31 <h1>{JSON.stringify(queryParam)}</h1>32 </div>33 );34}
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 👍.
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.