xxxxxxxxxx
import {withRouter} from 'react-router-dom';
const SomeComponent = withRouter(props => <MyComponent {props}/>);
class MyComponent extends React.Component {
SomeMethod () {
const {pathname} = this.props.location;
}
}
xxxxxxxxxx
const currentURL = window.location.href // returns the absolute URL of a page
const pathname = window.location.pathname //returns the current url minus the domain name
xxxxxxxxxx
import { useLocation } from 'react-router-dom';
function MyComponent() {
const location = useLocation();
const currentUrl = location.pathname;
console.log(currentUrl); // Prints the current URL to the console
return <div>Your component JSX goes here</div>;
}
xxxxxxxxxx
console.log(window.location.pathname); //yields: "/js" (where snippets run)
console.log(window.location.href); //yields: "https://stacksnippets.net/js"
Run code snippet
xxxxxxxxxx
import React from 'react';
const Component = () => {
const currentUrl = window.location.href;
return (
<div>
<p>The current URL is: {currentUrl}</p>
</div>
);
};
export default Component;