Table of Contents
Before jumping into examples, first, we will understand what is the difference between query parameters and URL parameters:
Consider the URL: https://example.com/search?term=pizza
Here, term
is the query parameter (or search parameter), which has a value of pizza
. URL parameters appear as key-value pairs.
So what are URL parameters? URL parameters are the ones that appear before the ?
in the URL.
https://example.com/orders/10001
In the above URL, 10001
is a URL parameter.
In URL parameters there will not be explicit mention of the key to which the value belongs.
It is up to the code to decide what 10001
represents based on the position or format of the URL.
Of course, when we read the URL as a human, we will understand they represent orderId
.
Reading Query parameters
We can retrieve the query part of the URL using location.search
.
That is, If I am on the page https://example.com/search?term=pizza&location=Bangalore
,
then calling location.search
would return ?term=pizza&location=Bangalore
.
But how do we extract key-value pairs from this? That is when URLSearchParams comes into the picture.
Using URLSearchParams
URLSearchParams help in parsing and accessing query parameters.
We can use the following code to get the value of term
:
1const queryParams = new URLSearchParams("?term=pizza&location=Bangalore")2const term = queryParams.get("term")3console.log(term) //pizza
We can loop though query parameters as shown in the code below:
1const queryParams = new URLSearchParams("?term=pizza&location=Bangalore")2for (const [key, value] of queryParams) {3 console.log({ key, value }) // {key: 'term', value: 'pizza'} {key: 'location', value: 'Bangalore'}4}
We can use this in a react component as shown below:
1function App() {2 const queryParams = new URLSearchParams(window.location.search)3 const term = queryParams.get("term")4 const location = queryParams.get("location")56 return (7 <div className="App">8 <p>Value of term: {term}</p>9 <p>Value of location: {location}</p>10 </div>11 )12}1314export default App
Now if you open http://localhost:3000/?term=pizza&location=Bangalore
, you will see the term and location displayed:
Using query-params package
We can make use of the query-string library to achieve the same thing.
First, install query-string using the following command (or npm i query-string
):
1yarn add query-string
We can use it in React as shown below:
1import queryString from "query-string"23function App() {4 const queryParams = queryString.parse(window.location.search)56 return (7 <div className="App">8 <p>Value of term: {queryParams.term}</p>9 <p>10 All query params <pre>{JSON.stringify(queryParams, null, 2)}</pre>11 </p>12 </div>13 )14}1516export default App
Now if you run the application, you will see the query parameters printed
The advantage of using query-string is that it returns a JavaScript Object and it has additional features.
Using React Router
If you are using React Router for routing in your application, then you can use the useSearchParams
hook.
First, install React Router in your project using the following command:
1yarn add history@5 react-router-dom@6
In index.js
, import the BrowserRouter
component and wrap it around the App component:
1import React from "react"2import ReactDOM from "react-dom"3import "./index.css"4import App from "./App"5import { BrowserRouter } from "react-router-dom"67ReactDOM.render(8 <React.StrictMode>9 <BrowserRouter>10 <App />11 </BrowserRouter>12 </React.StrictMode>,13 document.getElementById("root")14)
Create a component called Search
with the following code:
1import React from "react"2import { useSearchParams } from "react-router-dom"34const Search = () => {5 let [searchParams, setSearchParams] = useSearchParams()6 const term = searchParams.get("term")7 const location = searchParams.get("location")89 return (10 <div className="App">11 <p>Value of term: {term}</p>12 <p>Value of location: {location}</p>13 </div>14 )15}1617export default Search
Here we are making use of useSearchParams
to retrieve the query parameters.
The way of accessing the search parameters is the same as that of URLSearchParams
because useSearchParams
internally uses URLSearchParams
.
Finally, in App.js
create a route for the Search
component.
1import { Routes, Route } from "react-router-dom"2import Search from "./Search"34function App() {5 return (6 <div className="App">7 <Routes>8 <Route path="search" element={<Search />} />9 </Routes>10 </div>11 )12}1314export default App
Now if you open http://localhost:3000/search?term=pizza&location=Bangalore, you will see the search parameters printed:
You can learn more about react router in my previous article
Reading URL parameters
Since the URL parameter does not have explicit keys specified, we will have to make use of libraries like react router to access them.
We can make use of useParams
hook to access the URL parameters.
Create a component called Order
in your project which uses react router.
1import { useParams } from "react-router-dom"23export default function Order() {4 let params = useParams()5 return <h2>Order: {params.orderId}</h2>6}
Now update your route definition with the route order/:orderId
:
1import { Routes, Route } from "react-router-dom"2import Order from "./Order"34function App() {5 return (6 <div className="App">7 <Routes>8 <Route path="order/:orderId" element={<Order />} />9 </Routes>10 </div>11 )12}1314export default App
Note that :orderId
in route definition and orderId
in params.orderId
should match.
Now if you open http://localhost:3000/order/10001, you will see that the order id is being displayed:
If you want to learn programmatically routing, you can read more about it here.
If you have liked article, stay in touch with me by following me on twitter.
Leave a Comment