Skip to content

Instantly share code, notes, and snippets.

@thevolcanomanishere
Created July 28, 2022 11:20
Show Gist options
  • Save thevolcanomanishere/9ee4f966d93371e2be76fdea33415d0a to your computer and use it in GitHub Desktop.
Save thevolcanomanishere/9ee4f966d93371e2be76fdea33415d0a to your computer and use it in GitHub Desktop.
Detecting Tailwind breakpoints in Typescript
const DetectBreakpoint = () => {
const getCurrentBreakpoint = (): string => {
const breakpointUnknown: string = "unknown";
const breakpointSM: string | null =
document.getElementById("breakpoint-sm")?.offsetParent === null
? null
: "sm";
const breakpointMD: string | null =
document.getElementById("breakpoint-md")?.offsetParent === null
? null
: "md";
const breakpointLG: string | null =
document.getElementById("breakpoint-lg")?.offsetParent === null
? null
: "lg";
const breakpointXL: string | null =
document.getElementById("breakpoint-xl")?.offsetParent === null
? null
: "xl";
const breakpoint2XL: string | null =
document.getElementById("breakpoint-2xl")?.offsetParent === null
? null
: "2xl";
const breakpoint =
breakpointSM ??
breakpointMD ??
breakpointLG ??
breakpointXL ??
breakpoint2XL ??
breakpointUnknown;
return breakpoint;
};
const activateLightbox = () => {
const breakpoint = getCurrentBreakpoint();
const desktopBreakpoints: string[] = ["sm", "md", "lg", "xl", "2xl"];
console.log(breakpoint);
if (desktopBreakpoints.includes(breakpoint)) {
// We are on desktop
} else {
// We are on mobile :)
}
};
return (
<>
<div
id="breakpoint-sm"
className="hidden sm:block md:hidden lg:hidden xl:hidden 2xl:hidden w-0 h-0"
></div>
<div
id="breakpoint-md"
className="hidden sm:hidden md:block lg:hidden xl:hidden 2xl:hidden w-0 h-0"
></div>
<div
id="breakpoint-lg"
className="hidden sm:hidden md:hidden lg:block xl:hidden 2xl:hidden w-0 h-0"
></div>
<div
id="breakpoint-xl"
className="hidden sm:hidden md:hidden lg:hidden xl:block 2xl:hidden w-0 h-0"
></div>
<div
id="breakpoint-2xl"
className="hidden sm:hidden md:hidden lg:hidden xl:hidden 2xl:block w-0 h-0"
></div>
</>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment