Mobile vs. Desktop CSS switch for Web app with Server Side rendering

When modern web application is built using Server Side Rendering (SSR) or Static Site Generator (SSG) technology it is hard to decide which version, Mobile or Desktop, should be served.

If you are not planning to have separate domains or subdomains for mobile-first and desktop-first versions of your Web App, here is a useful trick:

  // In main App or Layout component add following:

  const isMobile = useMediaQuery({ maxWidth: 767 }); // From any library

  useEffect(() => {
    if (isMobile) {
      document.body.classList.remove('onDesktop');
      document.body.classList.add('onMobile');
    } else {
      document.body.classList.remove('onMobile');
      document.body.classList.add('onDesktop');
    }
  }, [isMobile]);

This is sample for React library, but can be easily implemented for any other frontend framework.

The idea is simple: to have .onMobile or .onDesktop CSS class modifier for the <body> tag

In that case mobile specific styles are .onMobile .abc {...} and desktop CSS is .onDesktop .abc {...}

Happy hacking 🙂

Author: BgRnD Official

Official representative of BgRnd Team on this website

Leave a Reply