databag/net/web/src/context/useViewportContext.hook.js
2022-08-17 11:18:20 -07:00

46 lines
1.3 KiB
JavaScript

import { useEffect, useState } from 'react';
export function useViewportContext() {
const [state, setState] = useState({ });
const SMALL_MEDIUM = 650;
const MEDIUM_LARGE = 1000;
const LARGE_XLARGE = 1400;
const updateState = (value) => {
setState((s) => ({ ...s, ...value }));
};
const handleResize = () => {
if (window.innerWidth < SMALL_MEDIUM) {
updateState({ display: 'small', width: window.innerWidth, height: window.innerHeight });
}
else if (window.innerWidth < MEDIUM_LARGE) {
updateState({ display: 'medium', width: window.innerWidth, height: window.innerHeight });
}
else if (window.innerWidth < LARGE_XLARGE) {
updateState({ display: 'large', width: window.innerWidth, height: window.innerHeight });
}
else {
updateState({ display: 'xlarge', width: window.innerWidth, height: window.innerHeight });
}
};
useEffect(() => {
for (let i = 0; i < 10; i++) {
setTimeout(handleResize, 100 * i); //cludge for my mobile browser
}
handleResize();
window.addEventListener('resize', handleResize);
window.addEventListener('orientationchange', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
window.removeEventListener('orientationchange', handleResize);
}
}, []);
return { state, actions: {} }
}