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
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.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.
If you’re using the React Router, you should be able to use the useLocation() method to get all of the route properties.
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
this could be the solution