In a React component, you can get the current URL using the window.location
object. Here’s how you can access the current URL:
import React from 'react';
function MyComponent() {
const currentURL = window.location.href;
return (
<div>
<p>Current URL: {currentURL}</p>
</div>
);
}
export default MyComponent;
In this example, window.location.href
provides the complete URL of the current page, including the protocol, domain, path, query parameters, and hash.
Please note that directly using window.location
in your React component may not be the most recommended practice if you’re dealing with complex routing and using libraries like react-router-dom
to manage your application’s routing. If you’re using react-router-dom
, it’s better to use the provided routing hooks and components to manage navigation and retrieve information about the current route.