Skip to content

Instantly share code, notes, and snippets.

@camilomontoyau
Last active April 8, 2020 17:42
Show Gist options
  • Save camilomontoyau/89410a22ae4e0b980ddd389da6f5bd48 to your computer and use it in GitHub Desktop.
Save camilomontoyau/89410a22ae4e0b980ddd389da6f5bd48 to your computer and use it in GitHub Desktop.
react hook for listening window resize event
function useBreadcrumbEllipsis(crumbs, windowWidth) {
if(!crumbs.length) {
return [];
}
let _crumbs = _.cloneDeep(crumbs);
let processedCrumbs = [];
let totalCharactersSize = 0;
let pastTotalCharactersSize = 0;
let maxCharactersSize = 0;
switch(true) {
case windowWidth >= 1350:
maxCharactersSize = 100;
break;
case windowWidth >= 1224 && windowWidth < 1350:
maxCharactersSize = 74;
break;
case windowWidth >= 1024 && windowWidth < 1224:
maxCharactersSize = 74;
break;
case windowWidth >= 944 && windowWidth < 1024:
maxCharactersSize = 65;
break;
case windowWidth >= 837 && windowWidth < 944:
maxCharactersSize = 56;
break;
case windowWidth >= 710 && windowWidth < 837:
maxCharactersSize = 40;
break;
case windowWidth >= 650 && windowWidth < 710:
maxCharactersSize = 52;
break;
case windowWidth >= 600 && windowWidth < 650:
maxCharactersSize = 48;
break;
default:
maxCharactersSize = 45;
}
for(let crumb of _crumbs) {
let {name = ''} = crumb;
console.log({name});
pastTotalCharactersSize = totalCharactersSize;
totalCharactersSize += name.length;
if(totalCharactersSize <= maxCharactersSize) {
processedCrumbs = [...processedCrumbs, crumb];
continue;
}
const lastNameCut = maxCharactersSize - pastTotalCharactersSize;
name = `${name.substring(0, lastNameCut)} ...`;
processedCrumbs = [...processedCrumbs, {...crumb, name}];
break;
}
return processedCrumbs;
}
function useWindowSize() {
const isClient = typeof window === 'object';
function getSize() {
return {
width: isClient ? window.innerWidth : undefined,
height: isClient ? window.innerHeight : undefined
};
}
const [windowSize, setWindowSize] = useState(getSize);
useEffect(() => {
if (!isClient) {
return false;
}
function handleResize() {
setWindowSize(getSize());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []); // Empty array ensures that effect is only run on mount and unmount
return windowSize;
}
export useWindowSize;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment