window.innerWidth in Next.js

The window object property is not defined in Next.js. If you want to read it, for example window.innerWidth, use the useEffect() Hook:

jsx
import { useEffect, useState } from 'react'

const Input = ({ width, setWidth }) => {

    const [max, setMax] = useState(0)

    useEffect(() => {

        setMax(window.innerWidth)
        
    }, [])

    return (
        <input 
            type = 'range' 
            min = '1' 
            max = {max} 
            value = {width} 
            onChange = {e => setWidth(e.target.value)}
        />
    )

}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.