score:45

Accepted answer

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.

score:1

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.

score:2

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.

score:11

You can also try

location.pathname

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

score:14

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

score:24

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


Related Query

More Query from same tag