How to get the current URL and pathname in React

Last updated on Sep 21, 2020 by Suraj Sharma



This tutorial is about how you can retrieve the pathname and the current URL of your React page.

I am going to discuss two different ways to get them in React.



1. Using window.location object


The simplest way to get the current URL and pathname in React is using a browser's window object.


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


2. React Router DOM


If your React App uses react-router-dom library for routing your single page application then there are few ways to extract the current pathname from the URL.


Using location props


When you write,


<Route path=”/home” component={Home} />

Implicity, location, match and history props are passed into the Home component.

These props can be accessed inside the Home component like this


import React from 'react';

const Home = (props) => {
  console.log(props.location);
  console.log(props.match);
  console.log(props.history);
  return <></>;
}

export default Home;

location, match and history props in react router dom


The above image shows all properties of location, match, and history props passed into the Home component.

Hence, props.location.pathname can get you the current URL pathname inside a React component.


Using useLocation() custom hook


If you are building a custom hook and require to access the custom URL or location, then you can use useLocation() hook provided by the react-router-dom v5.1 and beyond.

To get the current location or URL you can do like this


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

// custom hook to get the current pathname in React

const usePathname = () => {
  const location = useLocation();
  return location.pathname;
}


Conclusion


These were the two different ways to get the current URL pathname of a page in React.

If you haven’t used react-router-dom on your project then I would suggest you to use window.location object to get the pathname else props.location and useLocation() are the best options.



Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.