We can use the global window interface to get the current URL in React.
Specific Examples
Plain JavaScript approach
We need window.location to access the location object that contains information about the current URL, pathname, domain name, and more.
Here’s how to access the current URL value and log it to the console:
export default function Child(props) {
console.log(props.location.href);
return (
<div className="App">
<a href="/someURL">Some URL</a>
</div>
);
}
location object in react-router has the same properties as the one on window interface. In this case, we access the href property to log the full URL to the console.
This approach is good for class components where you can not use the useLocation() hook to access the location object.
Get current URL using react-router with useLocation() hook
In react-router version 6, we can use the useLocation() hook to get location object and current URL.
- Create a variable to hold the location object.
- Call the useLocation() hook, which returns the location object.
export default function App() {
const location = useLocation()
console.log(location.href);
return (
<div className="App">
<a href="/someURL">Some URL</a>
</div>
);
}
The location object has the same properties as the one passed down via props.
Note: To use the useLocation() prop, the component must be wrapped with a <Router> parent component.