9

I'm trying to access the URL subdomain. Traditionally in JavaScript I'd do

var full = window.location.host;
var parts = full.split('.');
var subdomain = parts[0];
// ...

However I'm calling this from a React JS component, and I get the following error -

Encountered error "TypeError: undefined is not an object (evaluating 'window.location.host')"

It seems as though window.location.host doesn't work from React? Does it not have access to the window?

I get there might be philosophical reasons to not do this, but I'd still be curious how to implement it if it's possible from React.

Thanks!

4
  • Is this code running in a browser? or is it possibly running in nodejs in some kind of isomorphic rendering mode? Commented May 19, 2016 at 18:11
  • So it's part of a larger Rails app. The react component is rendered from the view, which calls the JSX. I figured that although all of that gets compiled server-side, the end react code runs in the context of the browser on the client side? Commented May 19, 2016 at 18:14
  • We'd have to look at your specific setup, but my guess is this line with window.location is being evaluated on the back end where there is no window and no window object. Commented May 19, 2016 at 18:17
  • Yeah I think you're right, judging by the error and the fact that it returns "undefined" :( Commented May 19, 2016 at 18:24

1 Answer 1

4

This is isomorphic so if it is being processed server side so you cannot access the window.location.href

For server side, you will need to look at the underlying request object to get the hostname:

http://expressjs.com/en/api.html#req.hostname

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

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.