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?
Asked
Active
Viewed 1,090 times
3 Answers
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
-
1There 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.

Manish Yadav
- 11
- 3
-
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.

Martyn Compton
- 21
- 3