Skip to content

Commit

Permalink
fix window access during SSR
Browse files Browse the repository at this point in the history
  • Loading branch information
mayank99 committed Mar 26, 2024
1 parent aff5411 commit 7c47eb6
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions packages/itwinui-react/src/core/utils/hooks/useMediaQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,26 @@
*--------------------------------------------------------------------------------------------*/
import * as React from 'react';
import { useSyncExternalStore } from './useSyncExternalStore.js';
import { getWindow } from '../functions/dom.js';

export const useMediaQuery = (queryString: string) => {
const [getSnapshot, subscribe] = React.useMemo(() => {
const mediaQueryList = window.matchMedia(queryString);
const mediaQueryList = getWindow()?.matchMedia(queryString);

return [
() => mediaQueryList.matches,
() => mediaQueryList?.matches,
(onChange: () => void) => {
mediaQueryList.addEventListener?.('change', onChange);
mediaQueryList?.addEventListener?.('change', onChange);
return () => {
mediaQueryList.removeEventListener?.('change', onChange);
mediaQueryList?.removeEventListener?.('change', onChange);
};
},
];
}, [queryString]);

return useSyncExternalStore(
subscribe,
isClient ? getSnapshot : () => undefined,
typeof document !== 'undefined' ? getSnapshot : () => undefined,
() => undefined,
);
};

const isClient = typeof document !== 'undefined';

0 comments on commit 7c47eb6

Please sign in to comment.