PASSWORD RESET

Your destination for complete Tech news

How to get the current URL in React?

2.86K 0
< 1 min read

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.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.