Search code examples
reactjsreact-routerreact-router-dom

How to get the current "url" of a page using useLocation from 'react-router-dom'


I am currently trying to understand the url path of the current page of a react project using 'react-router-dom'. I want to print the url of the current location of the page I'm navigating.

This is how did it.

export default function useQuery () {
  const { search } = useLocation()

  return React.useMemo(() => new URLSearchParams(search), [search])
}
const query = useQuery()
console.log(query)

I want to know is there another method that i can print the current url path of the navigating page or can i use the useLocation method to find it.

PS: I'm using 'react-router-dom' version 5


Solution

  • there are several ways you can print the current URL path of the navigating page. One way is to use the window.location.pathname property to get the path portion of the current URL.

    console.log(window.location.pathname);
    

    If you're using React and React Router, you can also use the useLocation hook to get the current location object, which includes the pathname.

    import { useLocation } from 'react-router-dom';
    
    export default function App() {
      const location = useLocation();
      console.log(location.pathname);
    }