0

I wrote this code in next.js but I encountered an error. The error says "NextJS - ReferenceError: window is not defined". can you help me how can i fix it

function IconWeatherComponent({icon}) {
    
    let [svg, setSvg] = useState('');
    
    
    useEffect(() => {
        const setIcon = () => {
            if (icon === '01d') {
                setSvg('day.svg')
            }
            if (icon === '01n') {
                setSvg('night.svg')
            }
        setIcon();
    }, [icon])
    
    
    return (
        <div>
            <img src={`${window.location.origin}/weather-icons/${svg}`} width="70" height="70" alt=""/>
        </div>
    );
}

export default IconWeatherComponent
SelimSezer
  • 29
  • 6
  • 1
    Does this answer your question? [Window is not defined in Next.js React app](https://stackoverflow.com/questions/55151041/window-is-not-defined-in-next-js-react-app) – Konrad Dec 06 '22 at 20:28
  • Thinking on this further, do you really need to be accessing the window location? If these svg file are in the same project, you can import them directly into this component. That would be better unless for some reason you can't include those files in this repo. – charcole Dec 06 '22 at 20:51

2 Answers2

1

window is not defined at build time, so it can't be accessed directly in your JSX. It is only defined in the browser. You will need to check for the location only at runtime, in a useEffect hook.

function IconWeatherComponent({icon}) {
    
    let [svg, setSvg] = useState('');
    const [location, setLocation] = useState('');
    
    useEffect(() => {
        const setIcon = () => {
            if (icon === '01d') {
                setSvg('day.svg')
            }
            if (icon === '01n') {
                setSvg('night.svg')
            }
        setIcon();
    }, [icon])
    
    useEffect(() => {
        if (typeof window !== 'undefined') {
            setLocation(window.location.origin)
        }
    }, []
    
    return (
        <div>
            <img src={`${location}/weather-icons/${svg}`} width="70" height="70" alt=""/>
        </div>
    );
}

export default IconWeatherComponent
charcole
  • 143
  • 9
0

You want to access window object but in this solution window is not define. Add your code to a usseefect and save data to state.hope solve your problem

Usseefect (()=>{Setwindowlocation(window.location.origin)},[])
mostafa faryabi
  • 176
  • 1
  • 1
  • 11