DEV Community

loading...

Conditional rendering for responsiveness in SSR applications

lukem profile image Lukas Müller ・2 min read

I recently ran into a problem in a Gatsby site I'm building. In one of the pages, an element should only be visible in the desktop view, not on mobile devices. To achieve this, I wrote a utility function ...

const isMobile = () => window.innerWidth < 768
Enter fullscreen mode Exit fullscreen mode

... and then used that to conditionally render the element.

{ !isMobile() && <Element /> }
Enter fullscreen mode Exit fullscreen mode

This works fine in the local preview of the site, but I ran into problem in the statically built version. <Element> received faulty classnames from its immediate sibling. I wasn't able to find out the exact cause of this but I inferred it had something to do with SSR (server side rendering) + conditional rendering based on the following:

1) the problem doesn't happen in the client side rendered version
2) the only affected element is the conditionally rendered one

My solution was to go away from conditional rendering (in the React sense) and just not display the element in mobile breakpoints.

.element {
    &--invisible-on-mobile {
        @media (max-width: 768px) {
          display: none;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This works fine and to me it seems that this is also the better way to approach this. Here's why:

Based on my understanding, when using SSR, upon page load, the browser receives a proper HTML document filled with the full content of the page. This is different to a classic client side rendered SPA which is empty on page load except for a root container into which the frontend framework (React, Vue, etc.) renders the application. In this approach, it makes sense to conditionally render things because the browser starts with nothing and asks itself the question "I have not rendered anything yet. What do I want to show the user?". It can then choose what to render based on the applications' state.
In a static build, however, the whole content is there already, so the browser renders it immediately. The question then becomes: "What do I hide from the user?" This seems easier and cleaner to solve with CSS.

Is there a flaw in my understanding of SSR? Or is this indeed the better approach to what I'm trying to achieve?

Discussion (0)

pic
Editor guide