15

I've a little problem with reach router, using react hooks. I need capture the params of the route in the browser I tried with props of the native documentation in the web of reach router but that is not giving me the param, the route is this: http://localhost:8080/home?init=true

How to capture that variable "init"?

3
  • stackoverflow.com/questions/43216569/… Commented Oct 21, 2019 at 19:32
  • Yeah! Is correct! But, my question is based on reach router, not react router Commented Oct 21, 2019 at 20:59
  • Did you ever figure this out? Commented May 1, 2020 at 10:34

2 Answers 2

21

In no time, most of us will be redoing this everytime, so it's best to create a custom hook just to do this.

// A custom hook that builds on useLocation to parse // the query string for you. export const useQuery = queryParam => { const search = new URLSearchParams(useLocation().search); return search.get(queryParam); }; 
Sign up to request clarification or add additional context in comments.

1 Comment

This should be the answer, as it's the only one that doesn't require an additional library.
19

Reach Router has a useLocation hook you can use:

import { useLocation } from "@reach/router" // then const location = useLocation() 

In location.search is the search field, containing all the query parameters (query strings) from your URL. In your example, /home?init=true would return location.search: "?init=true", which is a query string.

You can use query-string library (yarn add query-string) to parse this:

import { parse } from "query-string" // then const searchParams = parse(location.search) 

which would give you object {init: "true"} you could also parse booleans with queryString.parse('foo=true', {parseBooleans: true})

So the full example would be

import { useLocation } from "@reach/router" import { parse } from "query-string" // and const location = useLocation() const searchParams = parse(location.search) // => {init: "true"} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.