DEV Community

Cover image for How to get Query Parameters and URL Parameters in React
collegewap
collegewap

Posted on • Originally published at codingdeft.com

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:



const queryParams = new URLSearchParams("?term=pizza&location=Bangalore")
const term = queryParams.get("term")
console.log(term) //pizza


Enter fullscreen mode Exit fullscreen mode

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'}
}


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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



yarn add query-string


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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:



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


Enter fullscreen mode Exit fullscreen mode

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")
)


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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.



import { useParams } from "react-router-dom"

export default function Order() {
  let params = useParams()
  return <h2>Order: {params.orderId}</h2>
}


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)