Skip to content

Instantly share code, notes, and snippets.

@cyrus01337
Created January 5, 2023 11:36
Show Gist options
  • Save cyrus01337/4e951efa0986ed6c1ec3c186f9232909 to your computer and use it in GitHub Desktop.
Save cyrus01337/4e951efa0986ed6c1ec3c186f9232909 to your computer and use it in GitHub Desktop.
Responsive component that conditionally renders based on resolution
import { useEffect, useState } from "react";
const MOBILE_WIDTH = 1024;
export const isDesktop = (limit = MOBILE_WIDTH) => window.innerWidth > limit;
export const isMobile = (limit = MOBILE_WIDTH) => window.innerWidth <= limit;2
const useResolutionChecker = ({ desktop, mobile }) => {
const [inMobileResolution, setInMobileResolution] = useState(isMobile());
useEffect(() => {
const listener = event => {
setInMobileResolution(isMobile());
};
window.addEventListener("resize", listener);
return () => window.removeEventListener("resize", listener);
});
if (mobile) {
return inMobileResolution;
} else if (desktop) {
return !inMobileResolution;
}
};
export function Desktop({ children }) {
const inDesktopResolution = useResolutionChecker({ desktop: true });
return inDesktopResolution ? children : null;
}
export function Mobile({ children }) {
const inMobileResolution = useResolutionChecker({ mobile: true });
return inMobileResolution ? children : null;
}
export default {
Desktop,
Mobile,
};
import Devices from "./Devices";
// if you solely want to check for resolution...
// import { isMobile } from "./Devices";
// or just want to do something conditionally for 1 device...
// import { Mobile } from "./Devices";
function ForMobile() {}
function ForDesktop() {}
function Content() {}
export default function Example() {
return (
<Content />
<Devices.Mobile>
<ForMobile />
</Devices.Mobile>
<Devices.Desktop>
<ForDesktop />
</Devices.Desktop>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment