For my use case, I mostly want to make things in JS respond at the same time and in the same way that bootstrap does.
The way bootstrap breakpoints work is that they apply if they are the given size or larger, and dont if they are smaller. You could do that with this library as it is, but you'd have to do the check yourself and have your own array of strings for size comparison.
Here is the code that I wrote to take a given breakpoint and return a boolean.
import debounce from 'debounce';
import { useEffect, useState } from 'react';
export const breakpoints = ['xs', 'sm', 'md', 'lg', 'xl', 'xxl'];
type Breakpoint = typeof breakpoints[number];
const resolveSize = (): Breakpoint => {
const width = window.innerWidth;
if (width < 576) {
return 'xs';
} else if (width >= 576 && width < 768) {
return 'sm';
} else if (width >= 768 && width < 992) {
return 'md';
} else if (width >= 992 && width < 1200) {
return 'lg';
} else if (width >= 1200 && width < 1440) {
return 'xl';
} else if (width >= 1440) {
return 'xxl';
}
return 'xxl';
};
const isLargerThanCutoff = (cutoff: Breakpoint): boolean => {
// Get the current breakpoint as a number
const currentSizeIndex = breakpoints.indexOf(resolveSize());
// Get the chosen breakpoint cutoff as a number
const cutoffIndex = breakpoints.indexOf(cutoff);
return currentSizeIndex >= cutoffIndex;
};
export const useBreakpoint = (cutoff: Breakpoint) => {
if (!breakpoints.includes(cutoff)) {
throw new Error(`Bad breakpoint size specified, use one of ${breakpoints}`);
}
const [passesCutoff, setPassesCutoff] = useState(() => isLargerThanCutoff(cutoff));
useEffect(() => {
const calcInnerWidth = debounce(function () {
setPassesCutoff(isLargerThanCutoff(cutoff));
}, 200);
window.addEventListener('resize', calcInnerWidth);
return () => window.removeEventListener('resize', calcInnerWidth);
}, []);
return passesCutoff;
};
export default useBreakpoint;
Might help someone! Thanks for the library!
For my use case, I mostly want to make things in JS respond at the same time and in the same way that bootstrap does.
The way bootstrap breakpoints work is that they apply if they are the given size or larger, and dont if they are smaller. You could do that with this library as it is, but you'd have to do the check yourself and have your own array of strings for size comparison.
Here is the code that I wrote to take a given breakpoint and return a boolean.
Might help someone! Thanks for the library!