Home > Software design >  ReferenceError: window is not defined error in next's
ReferenceError: window is not defined error in next's

Time:12-07

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

CodePudding user response:

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

CodePudding user response:

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)},[])
  • Related