'react router get full current path name

Is there an easy way to return the current router address.

IE, if I'm on page, and I just want to see what page I'm on according to the react router.

So, localhost/admin/users would return admin/users

Obviously, I can get the same results by parsing the location, but I was wondering if react router provides a simple mechanism to do this, the same way it provides the params props?



Solution 1:[1]

If you're using 1.0 or newer, you have the location as a prop in your React components that are matched against a route. So you just type

this.props.location.pathname

to get what you wanted.

Solution 2:[2]

this.props.location.pathname gives only the routing path.

window.location.href gives you the full URL, as suggested here https://stackoverflow.com/a/39823749/7560899

Solution 3:[3]

For React Functional Component

import { useLocation } from 'react-router-dom';

const MyComponent = () => {
  let location = useLocation();
  ...useState

    useEffect(() => {
    console.log(location.pathname);
  }, []);

  return ();

  };

  export default MyComponent;

There are many other options: https://dev.to/finallynero/hooks-introduced-in-react-router-v5-1-7g8

Solution 4:[4]

You can also try

location.pathname

It may work while other methods don't as it did to me

Solution 5:[5]

window.location will give the full path.

this.props.location.pathname - it may not give the full path. use this, if you want just the URL path without the domain prefix. (also, I may suggest using context API to get this in any child components instead of passing this as props)

one more example, to implement the new component with social share feature, you may need to use the window.location and not the location.pathname.

Solution 6:[6]

For a non-react, pure javascript based solution using the browser window object. Let's say the current page URL is something like this https://hostname:port/path?query.


window.location.href // returns the full URL 'https://hostname:port/path?query'

window.location.pathname // returns just the 'path' part of the full URL.

window.location.search // returns just the '?query' part of the full URL.

window.location.port // returns the 'port'.

window.location.hostname // returns just the 'hostname' part of the URL.

window.location.host // returns the hostname and port (hostname:port) part of the URL.

window.location.protocol // returns the protocol (https)

window.location.origin // returns the base URL (https://hostname:port)

See https://developer.mozilla.org/en-US/docs/Web/API/Location for more details.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ricardo Sanchez
Solution 2 Community
Solution 3 Paul Roub
Solution 4
Solution 5 Vinoth
Solution 6 k32y