How to Get the Current URL & other URL Properties in React

When building a web application with React, it's common to need to access the current URL of the application. This can be useful for a variety of purposes, such as dynamically rendering content based on the URL or updating the URL to reflect changes in the application state.

In this article, we'll go over how to get the current URL in React step by step.

Table of Contents

  1. Import the "useLocation" hook
  2. Use the "useLocation" hook
  3. Access other URL properties

Import the "useLocation" hook

React Router is a popular library for handling client-side routing in React applications. It provides a "useLocation" hook that we can use to access the current URL.
To use this hook, we first need to import it from the "react-router-dom" package. Add the following line at the top of your component file:

import { useLocation } from "react-router-dom";

Use the "useLocation" hook

Next, we can use the "useLocation" hook to get the current URL. The hook returns an object that contains information about the current URL, including the pathname, search query, and hash.

To access the current URL, we can simply call the hook in our component and destructure the "pathname" property from the returned object:

function MyComponent() {
  const { pathname } = useLocation();
  
  return (
    <div>
      Current URL: {pathname}
    </div>
  );
}

This will render a message that displays the current URL path.

Access other URL properties

In addition to the "pathname" property, the "useLocation" hook also returns "search" and "hash" properties, which represent the query string and hash fragment of the current URL, respectively.
If you need to access these properties, you can destructure them from the returned object as well:

function MyComponent() {
  const { pathname, search, hash } = useLocation();
  
  return (
    <div>
      Current URL: {pathname}
      <br />
      Search query: {search}
      <br />
      Hash fragment: {hash}
    </div>
  );
}

This will render a message that displays the current URL path, search query, and hash fragment.

That’s it. Thanks for reading.