Search code examples
reactjsnext.jscomponents

ReferenceError: window is not defined error in next's


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

Solution

  • 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