Created
December 31, 2020 10:14
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Public now