Search code examples
javascriptcssreactjsstyled-components

Issue with styled-components in "custom" single page application


I'm currently working on an old project, which has its "own way" of doing a single page application (does Ajax calls to an MVC application, gets the view, replaces the view client-side, appends styles and lots of other stuff!!), and although not ideal, currently I'm stuck with it!

I am trying to integrate an existing React application into this site, and what I'm doing is to use create-react-app and then build to create the bundles, and in the application, in the view begin returned from the server for a specific page, I'm putting script and link tags, pointing to my bundle files. It's worth noting that this server view is a partial ASP.NET MVC view, so my script and link tags are somehow part of the body.

I'm also using styled-components in my React application.

Now, here's the problem: when I first load the page I mentioned, my script is loaded, and I can see all my components being styled properly, but when I navigate in the existing custom SPA application, at some point, styles related to styled-components are messed up, and the only way to get them back is to reload the page.

I was inspecting the page, and I saw that styled-components is doing things with a custom link created in the head, and I see data-styled-components attribute being populated with custom class names as my components are loaded, but when the problem arises, in Chrome Developer Tools, I see that the link tag flashes as if it's changed, but it stays the same.

I have attached a GIF of the tag: - It starts with the initial page load - I navigate away and come back and I see more classes being appended - I repeat the step, and I only see that it flashes

I know the post is already long, but any help is deeply appreciated. Is it possible that, with the current infrastructure, it has something to do with the fact that whenever I come back to the page, a script tag is sent from the server pointing to my React bundle?

Screen capture of the tag used by <code>styled-components</code>


Solution

  • Thanks to Max Stoiber for answering in this GitHub issue:

    The reason for this behavior is exactly what I mentioned at the end of the question: every time the page is loaded, a script tag is sent from the server, containing the bundle, which in turn causes a new instance of styled-components to be created; this is not supported in styled-components, and that was the issue