Read the current full URL with React?

Reactjs

Reactjs Problem Overview


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

Reactjs Solutions


Solution 1 - Reactjs

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

Solution 2 - Reactjs

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!

Solution 3 - Reactjs

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.

Solution 4 - Reactjs

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

Solution 5 - Reactjs

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...

Solution 6 - Reactjs

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.

Solution 7 - Reactjs

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)

Solution 8 - Reactjs

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.

Solution 9 - Reactjs

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?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDougView Question on Stackoverflow
Solution 1 - ReactjsprobablyupView Answer on Stackoverflow
Solution 2 - ReactjslewdevView Answer on Stackoverflow
Solution 3 - ReactjsimrokView Answer on Stackoverflow
Solution 4 - Reactjsnorman123123View Answer on Stackoverflow
Solution 5 - ReactjsJamesView Answer on Stackoverflow
Solution 6 - Reactjsto240View Answer on Stackoverflow
Solution 7 - ReactjsAlex VargheseView Answer on Stackoverflow
Solution 8 - ReactjsNeeraj TangariyaView Answer on Stackoverflow
Solution 9 - ReactjsYurii HaiovyiView Answer on Stackoverflow