React/NextJS — SSR and Responsive Design
Published in
2 min readApr 27, 2022
I have ran into this for trying to build the responsive design with SSR feature in NextJS.
Here I captured the steps when I worked through to the end solution.
- tried to build responsive GridLayout. with different grid block
- used
react-device-detect
isMobile
to detect if it is mobile in javascript, and it would pass different contents to the relative grid block
3. react-device-detect
(it works by examining the User Agent string), so it may not good in here since we would like the responsive based on the width
4. found out another library react-responsive
5. realized that detect if it is mobile in Javascript doesn’t work with SSR because useMediaQuery
returned undefined in server side, server would not know the width of the window/browser
6. created DesktopConainter
and MobileContainer
with css media query
export const DesktopContainer = styled.div`
@media (max-width: 768px) {
display: none !important;
}
`;export const MobileContainer = styled.div`
@media (min-width: 769px) {
display: none !important;
}
`;
Final approach
- wrap the desktop content in
DesktopContainer
and mobile content inMobileContainer
- render both
Container
in server side - the browser will show/hide the
Container
based on the css media query on the client side
cons
- it will render both desktop and mobile container
div
, so there will be likely doublediv
element in the dom, which will affect the performance
- this is another approach which suggests by a few posts but I haven’t tried it yet