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/)
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.
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/`
You Can try!!
window.location.origin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With