skip to Main Content

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

3

Answers


  1. 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);
    }
    
    Login or Signup to reply.
  2. If you’re using the React Router, you should be able to use the useLocation() method to get all of the route properties.

    const location = useLocation();
    const { hash, pathname, search } = location;
    

    Otherwise you can simply use the window.location object that is automatically injected in all browsers
    window.location.pathname

    If you’re using the HashRouter, you should read the hash property

    Login or Signup to reply.
  3. console.log(window.location.pathname);
    

    this could be the solution

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search