Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@reach/router: how to get the current route / page?

How does one get the current route for reach router. In react router one would get that through the params?

The docs don't currently show an example how to do this.

like image 779
chrisjlee Avatar asked Jul 01 '19 15:07

chrisjlee


People also ask

How do I get the current route in my react router?

Use the useLocation() hook to get the current route with React Router, e.g. const location = useLocation() . The hook returns the current location object. For example, you can access the pathname as location. pathname .

How do I get the current page in react?

Use the window object to get the current URL in React, e.g. window. location. href returns a string containing the whole URL. If you need to access the path, use window.

How do you use navigate to be replaced?

option - replace Normally a call to navigate will push a new entry into the history stack so the user can click the back button to get back to the page. If you pass replace: true to navigate then the current entry in the history stack will be replaced with the new one.

How do you navigate with react dom on a router?

There are two ways to programmatically navigate with React Router - <Navigate /> and navigate() . You can get access to Navigate by importing it from the react-router-dom package and you can get access to navigate by using the custom useNavigate Hook.


2 Answers

Alternatively, use the useLocation hook (since 1.3.0):

import { useLocation } from "@reach/router"

const useAnalytics = () => {
    const location = useLocation()

    useEffect(() => {
        ga.send(['pageview', location.pathname])
    }, [])
}

Ref: https://reach.tech/router/api/useLocation

like image 175
ptim Avatar answered Sep 28 '22 06:09

ptim


Use the this.props.location as it's passed down to the component:

https://reach.tech/router/api/Router

like image 37
chrisjlee Avatar answered Sep 28 '22 06:09

chrisjlee