Skip to content

Instantly share code, notes, and snippets.

@karpolan
Created December 31, 2020 10:14
Show Gist options
  • Save karpolan/6d51bdfc612d731adb283f85e5959c1c to your computer and use it in GitHub Desktop.
Save karpolan/6d51bdfc612d731adb283f85e5959c1c to your computer and use it in GitHub Desktop.
React with Next/SSR/SSG, useful .onMobile or .onDestop class selector to apply different CSS styles
// In main App or Layout component add following:
const isMobile = useMediaQuery({ maxWidth: 767 }); // From react-responsive, Material UI or other styling library
useEffect(() => {
// Due to SSR/SSG we can not set 'app-layout onMobile' or 'app-layout onDesktop' on the server
// If we modify className using JS, we will got Warning: Prop `className` did not match. Server: "app-layout" Client: "app-layout onDesktop"
// So we have to apply document.body.class using the hook :)
if (isMobile) {
document.body.classList.remove('onDesktop');
document.body.classList.add('onMobile');
} else {
document.body.classList.remove('onMobile');
document.body.classList.add('onDesktop');
}
}, [isMobile]);
@karpolan
Copy link
Author

Public now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment