Skip to content

Commit 8379d11

Browse files
committed
Guard useMedia and MediaConsumer against non-browser environments, ensure early return for undefined window.
1 parent ec98c69 commit 8379d11

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

src/MediaConsumer/MediaConsumer.tsx

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ export const MediaConsumer = ({
1919
sizes
2020
}: IProps) => {
2121
const currentSize = useMedia(sizes);
22+
23+
if(!currentSize){
24+
return null;
25+
}
2226
return children(currentSize);
2327
};
2428

src/MediaConsumer/useMedia.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@ const useMedia = (sizes?: NoXsMediaSize[]) => {
1313
const breakpoints = theme[themeName]?.gridBreakpoints;
1414

1515
const getResize = () => {
16-
const width = typeof window !== 'undefined' ? window.innerWidth: 0;
16+
if(typeof window === 'undefined'){
17+
return null;
18+
}
19+
const width = window.innerWidth;
1720
let size: TMediaSize = 'xs';
1821

1922
if ((!sizes || sizes?.includes('xxl')) && width >= breakpoints.xxl) {
@@ -31,7 +34,7 @@ const useMedia = (sizes?: NoXsMediaSize[]) => {
3134
return size;
3235
};
3336

34-
const [currentSize, setCurrentSize] = useState<TMediaSize>(getResize());
37+
const [currentSize, setCurrentSize] = useState<TMediaSize|null>(getResize());
3538

3639
useEffect(() => {
3740
const handleResize = () => {

0 commit comments

Comments
 (0)