Answer the question
In order to leave comments, you need to log in
How to fix WebpackError: TypeError: window.matchMedia is not a function?
I encountered a problem when building the project, the matchMedia function does not start for the global window object. The project uses Gatsby / React. There is a custom hook for a certain screen width that works. When the project is running, everything works fine, but when I build the npm run build
Webpack project, it gives an error. How it is possible to eliminate this error?
const useMedia = (query) => {
const windowGlobal = typeof window !== 'undefined' && window
const [matches, setMatches] = useState(windowGlobal.matchMedia(query).matches)
useEffect(() => {
const media = windowGlobal.matchMedia(query)
if (media.matches !== matches) setMatches(media.matches)
const listener = () => setMatches(media.matches)
media.addEventListener('change', listener)
return () => media.removeEventListener('change', listener)
}, [matches, query])
return matches
}
const match = useMedia('(max-width: 575px)')
const changeLabel = match ? 'Cancel' : 'Add Now'
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question