342

How do I get the full URL from within a ReactJS component?

I'm thinking it should be something like this.props.location but it is undefined

10 Answers 10

500

window.location.href is what you're looking for.

Sign up to request clarification or add additional context in comments.

6 Comments

Please note that it may have problems on server side, if not configured properly.
I needed window.location for a feature that is client side. So I set the location in the state of my component onMount in order to avoid issues while rendering on server side.
it is not working. or kindly help me with structure of that in react. I used const ddd = window.location.href; console.log(ddd);
webpack will complain about this saying 'window is not defined'
@FranzSee yes there is no "window" in server-side code, so if that's your environment you'll need to use something like req.originalUrl from express or whatnot. The various react routing libraries that have SSR support have methods for getting this information.
|
187

If you need the full path of your URL, you can use vanilla Javascript:

window.location.href

To get just the path (minus domain name), you can use:

window.location.pathname

console.log(window.location.pathname); //yields: "/js" (where snippets run)
console.log(window.location.href);     //yields: "https://stacksnippets.net/js"

Source: Location pathname Property - W3Schools

If you are not already using "react-router" you can install it using:

yarn add react-router

then in a React.Component within a "Route", you can call:

this.props.location.pathname

This returns the path, not including the domain name.

Thanks @abdulla-zulqarnain!

1 Comment

you can do just like that for pathname window.location.pathname
73

window.location.href is what you need. But also if you are using react router you might find useful checking out useLocation and useHistory hooks. Both create an object with a pathname attribute you can read and are useful for a bunch of other stuff. Here's a youtube video explaining react router hooks

Both will give you what you need (without the domain name):

import { useHistory ,useLocation } from 'react-router-dom';
const location = useLocation()
location.pathname

const history = useHistory()
history.location.pathname

3 Comments

The question already said "with React", apparently window.location.href is not the React way.
this gives me an error, useHistory not found in react-router-dom
@johnk you are apperantly on react-router-dom version 6. useHistory no longer available with version 6. Checkout useNavigate stackoverflow.com/users/396483/john-k
49

this.props.location is a react-router feature, you'll have to install if you want to use it.

Note: doesn't return the full url.

1 Comment

Note: this does not return the full url (host name, protocol, etc.)
31

Plain JS :

window.location.href // Returns full path, with domain name
window.location.origin // returns window domain url Ex : "https://stackoverflow.com"
window.location.pathname // returns relative path, without domain name

Using react-router

this.props.location.pathname // returns relative path, without domain name

Using react Hook

const location = useLocation(); // React Hook
console.log(location.pathname); // returns relative path, without domain name

2 Comments

The URL is being asked for here, not just the path. The URL also includes query string and hash.
about useLocation actually it is quite dangerous advice - useLocation will trigger render if a location will be changed see docs reactrouter.com/en/main/hooks/use-location
15

You are getting undefined because you probably have the components outside React Router.

Remember that you need to make sure that the component from which you are calling this.props.location is inside a <Route /> component such as this:

<Route path="/dashboard" component={Dashboard} />

Then inside the Dashboard component, you have access to this.props.location...

1 Comment

And if your component is not inside a <Route /> you can use withRouter higher-order component.
11

Just to add a little further documentation to this page - I have been struggling with this problem for a while.

As said above, the easiest way to get the URL is via window.location.href.

we can then extract parts of the URL through vanilla Javascript by using let urlElements = window.location.href.split('/')

We would then console.log(urlElements) to see the Array of elements produced by calling .split() on the URL.

Once you have found which index in the array you want to access, you can then assigned this to a variable

let urlElelement = (urlElements[0])

And now you can use the value of urlElement, which will be the specific part of your URL, wherever you want.

Comments

9

Read this I found the solution of React / NextJs. Because if we use directly used the window.location.href in react or nextjs it throw error like

Server Error ReferenceError: window is not defined

import React, { useState, useEffect } from "react";
const Product = ({ product }) => {
 const [pageURL, setPageURL] = useState(0);
  useEffect(() => {
    setPageURL(window.location.href);
  })
  return (
     <div>
       <h3>{pageURL}</h3>
      </div>
  );
};

Note: https://medium.com/frontend-digest/why-is-window-not-defined-in-nextjs-44daf7b4604e#:~:text=NextJS%20is%20a%20framework%20that,is%20not%20run%20in%20NodeJS.

Comments

8

To get the current router instance or current location you have to create a Higher order component with withRouter from react-router-dom. otherwise, when you are trying to access this.props.location it will return undefined

Example

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';

class className extends Component {

      render(){
           return(
                ....
                  )
              }
}

export default withRouter(className)

Comments

1

As somebody else mentioned, first you need react-router package. But location object that it provides you with contains parsed url.

But if you want full url badly without accessing global variables, I believe the fastest way to do that would be

...

const getA = memoize(() => document.createElement('a'));
const getCleanA = () => Object.assign(getA(), { href: '' });

const MyComponent = ({ location }) => {
  const { href } = Object.assign(getCleanA(), location);

  ...

href is the one containing a full url.

For memoize I usually use lodash, it's implemented that way mostly to avoid creating new element without necessity.

P.S.: Of course is you're not restricted by ancient browsers you might want to try new URL() thing, but basically entire situation is more or less pointless, because you access global variable in one or another way. So why not to use window.location.href instead?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.