Search code examples
reactjsstyled-components

Give Client Generated Class Priority over Server Generated Class


We use "styled-components": "^4.1.3".

We generate some styled components based on a user-agent detector to work out if it's a mobile or desktop size. And we also do server rendering of styled components.

I've noticed that in the instance that a server css class is generated based on the server user-agent of the request (where it always defaults to mobile size) and then when the component is mounted on the client and its detected to be a desktop size, another class is created.

e.g.

/* sc-component-id: AppContainer__SearchBox-ct8bpk-1 */
.Rfqup{display:none;}.fQihLe{display:block;}

In this example if it's a desktop, we want to show SearchBox. As you can see 2 classes are created.

  • .Rfqup: in the server as size was detected to be mobile
  • .fQihLe in the client as the size was detected to be desktop

The issue I'm having is that the I want the client class to be applied instead of the server class - as that is the correct behaviour (i.e. user is on desktop).

But the server class is applied like so:

<div class="AppContainer__SearchBox-ct8bpk-1 Rfqup">

How can I instruct styled components to give preference to the client class "fQihLe"?

Thanks,


Solution

  • I was running into a similar issue where randomly some components looked fine on the ssr initial load, but a refresh or hmr generated a different className on the markup, so styles would be lost. Very strange.

    While this doesn't throw any errors, a symptom was this console warning (which went away after the fix was implemented):

    Warning: Expected server HTML to contain a matching <h1> in <div>
    

    Which again, was mega strange since the DOM was situation normal after I inspected it.

    Anyways, TLDR: this post from mattyfresh fixed it for me :)