stone
stone

Reputation: 8662

React-redux get site base URL / window.location

Hopefully this is a very simple question:

I want to create a string containing the full URL to a page on my site, like:

https://example.com/documents/1

Ideally I'd like to generate this in a react-redux connect()-ed container, in mapStateToProps(). Where the page is a grandchild of a react-router Route using browserHistory (so maybe I can get it from react-router or browserHistory somehow?) If necessary I'd do it in a full-on React class.

But I can't for the life of me find out how to do this. window (as in window.location) is always undefined in mapStateToProps() (no big surprise there) and in my view components' render() function.

So far I have only found ways to access the current route, e.g. "/documents/1", which is only a relative path and does not contain the site base url (https://example.com/)

Upvotes: 20

Views: 55373

Answers (4)

Mnengwa
Mnengwa

Reputation: 327

you can try the URL API. Take a look at this link for more details https://developer.mozilla.org/en-US/docs/Web/API/URL

const url = new URL("blob:https://mozilla.org:443/")
console.log(url.origin); 
// Logs 'https://mozilla.org'

Upvotes: -2

Kunal Soni
Kunal Soni

Reputation: 151

You Can try!!

window.location.origin

Upvotes: 10

Denis S Dujota
Denis S Dujota

Reputation: 611

After componentDidMount you can have direct access to the origin location so that you can get the root url.

I use the below code in my JSX all the time so that i dont have to worry about the root path ex: dev env this would be localhost:3000/whatever, staging this will be AppStaging.heroku/whatever/..... and in production it would evaluate to www.myapp.com/whatever

`${window.location.origin.toString()}/whateverRoute/`

Upvotes: 15

David Gilbertson
David Gilbertson

Reputation: 4883

So firstly, remember your code runs on client and server so any access to window needs to be wrapped in a check.

  if (typeof window !== 'undefined') {
    var path = location.protocol + '//' + location.host + '/someting'; // (or whatever)
  } else {
    // work out what you want to do server-side...
  }

If the URL you generate shows in the DOM, and on the client you populate the store with this URL before the first render, you're going to get a checksum error. If you really want to avoid the error you can wait until componentDidMount() in your root component to get/set the url.

Upvotes: 31

Related Questions