databag/net/web/src/context/useViewportContext.hook.js

46 lines
1.3 KiB
JavaScript
Raw Normal View History

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