Skip to content

Instantly share code, notes, and snippets.

@scorsi
Last active April 30, 2020 14:47
Show Gist options
  • Save scorsi/bca37858f130f64e394ac47e563eb46b to your computer and use it in GitHub Desktop.
Save scorsi/bca37858f130f64e394ac47e563eb46b to your computer and use it in GitHub Desktop.
Get window width and match
import {useEffect, useState} from 'react';
const getWindowDimensions = () => {
const {innerWidth: width, innerHeight: height} = window;
return {
width,
height
};
};
export const useWindowDimensions = () => {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
useEffect(() => {
const handleResize = () => {
setWindowDimensions(getWindowDimensions());
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowDimensions;
};
import {useEffect, useState} from 'react';
import {useWindowDimensions} from "./useWindowDimensions";
const _sizes = {
xs: (w: number) => w < 576,
sm: (w: number) => w >= 576 && w < 768,
md: (w: number) => w >= 768 && w < 992,
lg: (w: number) => w >= 992 && w < 1200,
xl: (w: number) => w >= 1200 && w < 1600,
xxl: (w: number) => w >= 1600,
};
export const useWindowWidthMatch = (sizes: ("xs" | "sm" | "md" | "lg" | "xl" | "xxl")[]) => {
const {width} = useWindowDimensions();
const [match, setMatch] = useState(false);
useEffect(() => {
setMatch(false);
for (let i = 0; i < sizes.length; i++) {
if (_sizes[sizes[i]](width)) {
setMatch(true);
break;
}
}
}, [sizes, width]);
return match;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment