Skip to content
react

How to get Query Parameters and URL Parameters in React

Dec 10, 2022Abhishek EH5 Min Read
How to get Query Parameters and URL Parameters in React

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:

App.js
1function App() {
2 const queryParams = new URLSearchParams(window.location.search)
3 const term = queryParams.get("term")
4 const location = queryParams.get("location")
5
6 return (
7 <div className="App">
8 <p>Value of term: {term}</p>
9 <p>Value of location: {location}</p>
10 </div>
11 )
12}
13
14export default App

Now if you open http://localhost:3000/?term=pizza&location=Bangalore, you will see the term and location displayed:

Query Params using URLSearchParams

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:

App.js
1import queryString from "query-string"
2
3function App() {
4 const queryParams = queryString.parse(window.location.search)
5
6 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}
15
16export default App

Now if you run the application, you will see the query parameters printed

query string

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:

index.js
1import React from "react"
2import ReactDOM from "react-dom"
3import "./index.css"
4import App from "./App"
5import { BrowserRouter } from "react-router-dom"
6
7ReactDOM.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"
3
4const Search = () => {
5 let [searchParams, setSearchParams] = useSearchParams()
6 const term = searchParams.get("term")
7 const location = searchParams.get("location")
8
9 return (
10 <div className="App">
11 <p>Value of term: {term}</p>
12 <p>Value of location: {location}</p>
13 </div>
14 )
15}
16
17export 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.

App.js
1import { Routes, Route } from "react-router-dom"
2import Search from "./Search"
3
4function App() {
5 return (
6 <div className="App">
7 <Routes>
8 <Route path="search" element={<Search />} />
9 </Routes>
10 </div>
11 )
12}
13
14export default App

Now if you open http://localhost:3000/search?term=pizza&location=Bangalore, you will see the search parameters printed:

Query Params using React router

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.

Order.js
1import { useParams } from "react-router-dom"
2
3export 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"
3
4function App() {
5 return (
6 <div className="App">
7 <Routes>
8 <Route path="order/:orderId" element={<Order />} />
9 </Routes>
10 </div>
11 )
12}
13
14export 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:

URL params react router

If you want to learn programmatically routing, you can read more about it here.

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com