简体   繁体   中英

ReferenceError: window is not defined w/ useMedia() hook + next.js

Because I am using next.js I think I'm getting a "window is not defined" error due to code executing on the server side rather than on the client. I tried using useLayoutEffect() to wait for the page to render but it still didn't work. Is there anything I can do to change the custom useMedia() hook below to fix this issue?

export default (queries, values, defaultValue) => {
  const mediaQueryLists = queries.map(q => window.matchMedia(q));

  const getValue = () => {
    const index = mediaQueryLists.findIndex(mql => mql.matches);

    return typeof values[index] !== "undefined" ? values[index] : defaultValue;
  };

  const [value, setValue] = useState(getValue);
  useEffect(() => {
    const handler = () => setValue(getValue);

    mediaQueryLists.forEach(mql => mql.addListener(handler));

    return () => mediaQueryLists.forEach(mql => mql.removeListener(handler));
  }, []);

  return value;
};

Because the window doesn't mount on time try to wait for it using:

let mediaQueryLists
if (typeof window !== 'undefined') {
  mediaQueryLists = queries.map(q => window.matchMedia(q));
} else {
  mediaQueryLists = []
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM