How to get Query Parameters and URL Parameters in React
Tags: react
Published: 2022-07-18 15:08:01

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](https://developer.mozilla.org/en-US/docs/Web/API/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`:

```js
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:

```js
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:

```jsx
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:

![Query Params using URLSearchParams](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/djbc9y4cmvytl1kdpwr8.png)

### Using query-params package

We can make use of the [query-string](https://www.npmjs.com/package/query-string) library to achieve the same thing. First, install query-string using the following command (or `npm i query-string`):

```bash
yarn add query-string
```

We can use it in React as shown below:

```jsx
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

![query string](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r3ipkrx5ojuu97488hhz.png) 

The advantage of using query-string is that it returns a JavaScript Object and it has [additional features](https://github.com/sindresorhus/query-string#api).

### 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:

```bash
yarn add history@5 react-router-dom@6
```

In `index.js`, import the `BrowserRouter` component and wrap it around the App component:

```jsx
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:

```jsx
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.

```jsx
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](http://localhost:3000/search?term=pizza&location=Bangalore), you will see the search parameters printed:

![Query Params using React router](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dz8gn5yapn3fsm39x804.png) 

> You can learn more about react router in my [previous article](https://www.codingdeft.com/posts/react-router-tutorial/)

## 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.

```jsx
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`:

```jsx
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](http://localhost:3000/order/10001), you will see that the order id is being displayed:

![URL params react router](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b63wb57a863gp8jqzwfe.png) 

If you want to learn programmatically routing, you can read more about it [here](https://www.codingdeft.com/posts/react-router-tutorial/#passing-url-parameters-to-a-route).