0

I am working on ReactJs and the server direct to a domain name with id on it. So I want to ask how can I get current domain name with ReactJS?

Tong
  • 77
  • 2
  • 11
  • 1
    Does this answer your question? [how to get the host url using javascript from the current page](https://stackoverflow.com/questions/6042007/how-to-get-the-host-url-using-javascript-from-the-current-page) – keul Feb 12 '20 at 10:03

3 Answers3

2

This isn't React specific.

Just look at window.location:

alert(window.location.hostname)

(Yes, the above snippet will say stacksnippets.net due to security reasons.)

AKX
  • 152,115
  • 15
  • 115
  • 172
  • Thanks, but I got this error: `ReferenceError: window is not defined`. It is jsdom jsdom-global library right? – Tong Feb 12 '20 at 10:07
  • `window` is innately available in browsers, you don't need a library. Are you running this in JSDom? – AKX Feb 12 '20 at 10:23
  • I found the answer. I use `context.req.url` of `getInitialProps` ReactJS, so I dont have to use `window`. – Tong Feb 12 '20 at 13:37
  • 1
    There is no "context.req.url" in raw ReactJS, so you left essential detail out of your original question. Glad you found the answer though. – AKX Feb 12 '20 at 14:40
1

Use window.location inside componentDidMount React Lifecycle. If you want to use inside DOM use state to store value.

  • I found the answer. I use `context.req.url` of `getInitialProps` ReactJS, so I dont have to use `window`. – Tong Feb 12 '20 at 13:38
1

Use window.location.hostname - note this will not work in JSDom, only in browsers.