Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get parameters on Reach Router

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

like image 936
David Acevedo Avatar asked Oct 21 '19 19:10

David Acevedo


People also ask

How do I find the URL parameters on a router?

Getting the URL params In React router v4, you can access it using the props.match.params.id . In class-based components, you can access it like this. import React, { Component } from "react"; class Users extends Component { render() { const { id } = this.

How do I get query params in react-router-dom?

Get a single Query String value location.search object: import React from 'react'; import { useSearchParams } from 'react-router-dom'; const Users = () => { const [searchParams] = useSearchParams(); console. log(searchParams); // ▶ URLSearchParams {} return <div>Users</div>; };


2 Answers

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"}
like image 193
sunapi386 Avatar answered Oct 09 '22 12:10

sunapi386


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);
    };
like image 42
Asim K T Avatar answered Oct 09 '22 12:10

Asim K T