Skip to content

Commit

Permalink
Fix unstyled content flash
Browse files Browse the repository at this point in the history
We need to handle styled components at the server level for remix.
  • Loading branch information
cronokirby committed Oct 22, 2024
1 parent 18fb3c3 commit c422ed1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 14 deletions.
31 changes: 31 additions & 0 deletions app/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -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(
<RemixServer context={remixContext} url={request.url} />,
),
);
const styles = sheet.getStyleTags();

markup = markup.replace("__STYLES__", styles);

responseHeaders.set("Content-Type", "text/html");

return new Response("<!DOCTYPE html>" + markup, {
status: responseStatusCode,
headers: responseHeaders,
});
}
18 changes: 4 additions & 14 deletions app/root.tsx
Original file line number Diff line number Diff line change
@@ -1,40 +1,30 @@
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 (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
{typeof document === "undefined" ? "__STYLES__" : null}
</head>
<body>
{children}
<ScrollRestoration />
<Scripts />
<LiveReload />
</body>
</html>
);
Expand Down

0 comments on commit c422ed1

Please sign in to comment.