Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/)

like image 420
stone Avatar asked Jul 20 '16 23:07

stone


3 Answers

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.

like image 137
David Gilbertson Avatar answered Oct 06 '22 02:10

David Gilbertson


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/`
like image 27
Denis S Dujota Avatar answered Oct 06 '22 01:10

Denis S Dujota


You Can try!!

window.location.origin
like image 31
Kunal Soni Avatar answered Oct 06 '22 02:10

Kunal Soni