React/NextJS — SSR and Responsive Design

Fred Wong
fredwong-it
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.

  1. tried to build responsive GridLayout. with different grid block
  2. 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 useMediaQueryreturned 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 in MobileContainer
  • 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 double div element in the dom, which will affect the performance

@artsy/fresnel

  • this is another approach which suggests by a few posts but I haven’t tried it yet

Reference:

--

--