How to get Query Parameters and URL Parameters in React
collegewap
Posted on July 18, 2022
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
:
const queryParams = new URLSearchParams("?term=pizza&location=Bangalore")
const term = queryParams.get("term")
console.log(term) //pizza
We can loop though query parameters as shown in the code below:
const queryParams = new URLSearchParams("?term=pizza&location=Bangalore")
for (const [key, value] of queryParams) {
console.log({ key, value }) // {key: 'term', value: 'pizza'} {key: 'location', value: 'Bangalore'}
}
We can use this in a react component as shown below:
function App() {
const queryParams = new URLSearchParams(window.location.search)
const term = queryParams.get("term")
const location = queryParams.get("location")
return (
<div className="App">
<p>Value of term: {term}</p>
<p>Value of location: {location}</p>
</div>
)
}
export 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
):
yarn add query-string
We can use it in React as shown below:
import queryString from "query-string"
function App() {
const queryParams = queryString.parse(window.location.search)
return (
<div className="App">
<p>Value of term: {queryParams.term}</p>
<p>
All query params <pre>{JSON.stringify(queryParams, null, 2)}</pre>
</p>
</div>
)
}
export 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:
yarn add history@5 react-router-dom@6
In index.js
, import the BrowserRouter
component and wrap it around the App component:
import React from "react"
import ReactDOM from "react-dom"
import "./index.css"
import App from "./App"
import { BrowserRouter } from "react-router-dom"
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById("root")
)
Create a component called Search
with the following code:
import React from "react"
import { useSearchParams } from "react-router-dom"
const Search = () => {
let [searchParams, setSearchParams] = useSearchParams()
const term = searchParams.get("term")
const location = searchParams.get("location")
return (
<div className="App">
<p>Value of term: {term}</p>
<p>Value of location: {location}</p>
</div>
)
}
export 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.
import { Routes, Route } from "react-router-dom"
import Search from "./Search"
function App() {
return (
<div className="App">
<Routes>
<Route path="search" element={<Search />} />
</Routes>
</div>
)
}
export 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.
import { useParams } from "react-router-dom"
export default function Order() {
let params = useParams()
return <h2>Order: {params.orderId}</h2>
}
Now update your route definition with the route order/:orderId
:
import { Routes, Route } from "react-router-dom"
import Order from "./Order"
function App() {
return (
<div className="App">
<Routes>
<Route path="order/:orderId" element={<Order />} />
</Routes>
</div>
)
}
export 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.
Posted on July 18, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.