I would like to return {window.location.host} on a static next.js website
I managed to log the value but I can not figure out how to return it.
import React from "react";
import { useEffect } from "react";
export default function Test() {
useEffect(() => {
console.log(window.location.host);
}, []);
return <h1>{window.location.host}</h1>;
}
I’m a JS beginner, all I managed was to return it once on the initial page load with useEffect but after a reload it gives the error
ReferenceError: window is not defined
>Solution :
window is unavailable during server side rendering, you can a state hook and update it in your effect hook client side.
import {useEffect, useState} from "react";
export default function TestPage() {
const [host, setHost] = useState("");
useEffect(() => {
if (typeof window !== "undefined") setHost(window.location.host);
}, []);
return <h1>{host}</h1>;
}