Query strings in JavaScript and React
The query component (or query string) is part of a URI and contains data in the form of key value pairs.
The query string in this URI is ?format=full
(Image adapted from the URI syntax as written by IETF).
The query string is also referred to as the "search string".
There are a number of ways to interact with the query string using JavaScript, which are detailed below.
Vanilla JS
The Location
interface has a property called search
.
window.location.search // Returns ?format=full
You can then pass this string to the URLSearchParams
to easily parse out the values in the query string.
// https://rw.codes/tutorials?format=fullconst queryString = window.location.searchconst params = new URLSearchParams(queryString)const action = params.get('format') // Returns "full"
The query-string library
We can abstract this away a little bit by introducing the query-string
library by @sindresorhus.
By passing the search string to query-string's parse
method, we get back a familiar JavaScript object.
const parsed = queryString.parse(window.location.search)console.log(parsed.format)// "full"
This amazing library has a bunch of other useful functions as well, so I recommend reading the documentation to see other ways to use it.
React
All of the above methods will also work in a React context, however, various React routers often provide their own convenience methods and hooks to interact with the query string.
use-query-params
https://github.com/pbeshai/use-query-params
NextJS
{!} — This may need some more details, and might only work in SSR. There's also potentially other ways to do it. https://stackoverflow.com/questions/43862600/how-can-i-get-query-string-parameters-from-the-url-in-next-js
The NextJS router offers a hook, useRouter
that is a joy to use.
// https://rw.codes/tutorials?format=fullimport { useRouter } from 'next/router'export default function Page() {const router = useRouter()const format = router.query.formatreturn <span>{format}</span> // Renders the text "full"}
The router object has a query
property that returns the query string parsed to an object.
React router and Reach router
React router and Reach router provide hooks for location
but beyond that it's up to us to parse the search string.
// https://rw.codes/tutorials?format=fullimport { parse } from "query-string"import { useLocation } from "@reach/router"export default function Page() {const location = useLocation()const params = parse(location.search)return <span>{params.format}</span> // Renders the text "full"}
Not to be confused with route parameters (url parameters)
Route params (also known as URL params) and query strings are not the same thing. Query strings are part of the standardized URI components, whereas url params are a JavaScript framework routing paradigm.
It can be hard to filter through search results when looking for tutorials or information on these topics, so keep an eye on the wording.
Here's an exampled of a route param, where :invoiceId
is a dynamic path that changes.
path = "invoices/:invoiceId"
You can learn more about route params by reading the Reach docs or this ScotchIO tutorial, "Using React Router 4 — Route Params".
Sources:
- https://stackoverflow.com/questions/58492797/how-to-get-parameters-on-reach-router
- https://stackoverflow.com/questions/35352638/react-how-to-get-parameter-value-from-query-string
- https://en.wikipedia.org/wiki/Query_string
- https://tools.ietf.org/html/rfc3986#section-3.4
- https://html.spec.whatwg.org/multipage/history.html#dom-location-search