Server-side rendering
The getSandpackCssText function, which is available in the main package, is responsible for getting the Sandpack CSS string and server-side render it. Furthermore, Sandpack uses stitches/core under the hood to generate and dedupe theme variation, ensuring a consistent and lightweight CSS output.
import { getSandpackCssText } from "@codesandbox/sandpack-react";
const cssTextOutput = getSandpackCssText();
How to use it
Here's some examples of how to use in some popular React frameworks.
💡
Reminder
For a better hydration strategy, we highly recommend adding an id="sandpack"
to your style tag.
Next.js
// examples/nextjs/pages/_document.tsx
import { getSandpackCssText } from "@codesandbox/sandpack-react";
import { Html, Head, Main, NextScript } from "next/document";
export default function Document() {
return (
<Html>
<Head>
<style
dangerouslySetInnerHTML={{ __html: getSandpackCssText() }}
id="sandpack"
key="sandpack-css"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
Gatsby
// examples/gatsby/gatsby-ssr.js
import * as React from "react";
import { getSandpackCssText } from "@codesandbox/sandpack-react";
export const onRenderBody = ({ setHeadComponents }) => {
setHeadComponents([
<style
id="sandpack"
key="sandpack-css"
dangerouslySetInnerHTML={{
__html: getSandpackCssText(),
}}
/>,
]);
};
Examples
Still not clear, take a look at these examples.