How to get the current URL in React.js

When working in a React.js project, there are many times where we need to access the URL in order to change a specific piece of state. Typically, a React project will utilize React router for all of its URL and routing logic.

However, some times we just need to access the URL regardless of whether React Router is being used. So, how exactly can you get the current URL in React.js?

Thankfully this is relatively simple just by accessing the window object.

window.location.href

This will give you access to the window ‘s location object and the value of the URL in it.

This will give you the full path of the URL and can be accessed anywhere in the React component:

class Header extends React.Component {
 
 componentDidMount() {
    console.log(window.location.href);
  }
 
 render() {
    return (
      <div>
        <h3>Hello world!</h3>
      </div>
    );
  }
}
 
Proudly published with Gatsby