From c422ed1008a2c022c0e77bd227ad0d6f67163d65 Mon Sep 17 00:00:00 2001 From: Lucas Meier Date: Tue, 22 Oct 2024 10:33:49 -0700 Subject: [PATCH] Fix unstyled content flash We need to handle styled components at the server level for remix. --- app/entry.server.tsx | 31 +++++++++++++++++++++++++++++++ app/root.tsx | 18 ++++-------------- 2 files changed, 35 insertions(+), 14 deletions(-) create mode 100644 app/entry.server.tsx diff --git a/app/entry.server.tsx b/app/entry.server.tsx new file mode 100644 index 0000000..82c123f --- /dev/null +++ b/app/entry.server.tsx @@ -0,0 +1,31 @@ +// c.f. https://github.com/remix-run/examples/blob/main/styled-components/app/entry.server.tsx +import type { AppLoadContext, EntryContext } from "@remix-run/node"; +import { RemixServer } from "@remix-run/react"; +import { renderToString } from "react-dom/server"; +import { ServerStyleSheet } from "styled-components"; + +export default function handleRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + remixContext: EntryContext, + loadContext: AppLoadContext, +) { + const sheet = new ServerStyleSheet(); + + let markup = renderToString( + sheet.collectStyles( + , + ), + ); + const styles = sheet.getStyleTags(); + + markup = markup.replace("__STYLES__", styles); + + responseHeaders.set("Content-Type", "text/html"); + + return new Response("" + markup, { + status: responseStatusCode, + headers: responseHeaders, + }); +} diff --git a/app/root.tsx b/app/root.tsx index 61c8b98..29a91f2 100644 --- a/app/root.tsx +++ b/app/root.tsx @@ -1,28 +1,16 @@ import { Links, + LiveReload, Meta, Outlet, Scripts, ScrollRestoration, } from "@remix-run/react"; -import type { LinksFunction } from "@remix-run/node"; import "./tailwind.css"; -export const links: LinksFunction = () => [ - { rel: "preconnect", href: "https://fonts.googleapis.com" }, - { - rel: "preconnect", - href: "https://fonts.gstatic.com", - crossOrigin: "anonymous", - }, - { - rel: "stylesheet", - href: "https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap", - }, -]; - export function Layout({ children }: { children: React.ReactNode }) { + // The __STYLES__ hook provides a place to inject the server rendered styles. return ( @@ -30,11 +18,13 @@ export function Layout({ children }: { children: React.ReactNode }) { + {typeof document === "undefined" ? "__STYLES__" : null} {children} + );