Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(examples): Add Emotion example #1485

Merged
merged 14 commits into from
Feb 25, 2022
Merged
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
- graham42
- GregBrimble
- hardingmatt
- helderburato
- HenryVogt
- hkan
- Holben888
Expand Down
6 changes: 6 additions & 0 deletions examples/emotion/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
node_modules

/.cache
/build
/public/build
.env
33 changes: 33 additions & 0 deletions examples/emotion/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Example app with [emotion](https://emotion.sh/)

This example features how to use [emotion](https://emotion.sh/) with Remix.

## Preview

Open this example on [CodeSandbox](https://codesandbox.io/):

[![Open in CodeSandbox](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/github/remix-run/remix/tree/main/examples/emotion)

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `app/routes/index.tsx`. The page auto-updates as you edit the file.

## Commands

- `dev`: runs your application on `localhost:3000`
- `build`: creates the production build version
- `start`: starts a simple server with the build production code

## Related Links

[Emotion](https://emotion.sh/)
31 changes: 31 additions & 0 deletions examples/emotion/app/entry.client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { hydrate } from "react-dom";
import { RemixBrowser } from "remix";
import React, { useState } from "react";
import { CacheProvider } from "@emotion/react";
import createEmotionCache from "./styles/createEmotionCache";
import ClientStyleContext from "./styles/client.context";

interface ClientCacheProviderProps {
children: React.ReactNode;
}

function ClientCacheProvider({ children }: ClientCacheProviderProps) {
const [cache, setCache] = useState(createEmotionCache());

function reset() {
setCache(createEmotionCache());
}

return (
<ClientStyleContext.Provider value={{ reset }}>
<CacheProvider value={cache}>{children}</CacheProvider>
</ClientStyleContext.Provider>
);
}

hydrate(
<ClientCacheProvider>
<RemixBrowser />
</ClientCacheProvider>,
document
);
43 changes: 43 additions & 0 deletions examples/emotion/app/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { renderToString } from "react-dom/server";
import { RemixServer } from "remix";
import type { EntryContext } from "remix";

import createEmotionServer from "@emotion/server/create-instance";
import { CacheProvider } from "@emotion/react";
import createEmotionCache from "./styles/createEmotionCache";
import ServerStyleContext from "./styles/server.context";

export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
const cache = createEmotionCache();
const { extractCriticalToChunks } = createEmotionServer(cache);

const html = renderToString(
<ServerStyleContext.Provider value={null}>
<CacheProvider value={cache}>
<RemixServer context={remixContext} url={request.url} />
</CacheProvider>
</ServerStyleContext.Provider>
);

const chunks = extractCriticalToChunks(html);

const markup = renderToString(
<ServerStyleContext.Provider value={chunks.styles}>
<CacheProvider value={cache}>
<RemixServer context={remixContext} url={request.url} />
</CacheProvider>
</ServerStyleContext.Provider>
);

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

return new Response(`<!DOCTYPE html>${markup}`, {
status: responseStatusCode,
headers: responseHeaders
});
}
111 changes: 111 additions & 0 deletions examples/emotion/app/root.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import {
Links,
LiveReload,
Meta,
Outlet,
Scripts,
ScrollRestoration,
useCatch
} from "remix";
import { useContext, useEffect } from "react";
import { withEmotionCache } from "@emotion/react";
import ServerStyleContext from "./styles/server.context";
import ClientStyleContext from "./styles/client.context";
import type { MetaFunction } from "remix";

import styled from "@emotion/styled";

const Container = styled("div")`
background-color: #ff0000;
padding: 1em;
`;

export const meta: MetaFunction = () => {
return { title: "Remix with Emotion" };
};

interface DocumentProps {
children: React.ReactNode;
title?: string;
}

const Document = withEmotionCache(
({ children, title }: DocumentProps, emotionCache) => {
const serverStyleData = useContext(ServerStyleContext);
const clientStyleData = useContext(ClientStyleContext);

// Only executed on client
useEffect(() => {
// re-link sheet container
emotionCache.sheet.container = document.head;

// re-inject tags
const tags = emotionCache.sheet.tags;
emotionCache.sheet.flush();
tags.forEach(tag => {
(emotionCache.sheet as any)._insertTag(tag);
});

// reset cache to reapply global styles
clientStyleData.reset();
}, []);

return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
{title ? <title>{title}</title> : null}
<Meta />
<Links />
{serverStyleData?.map(({ key, ids, css }) => (
<style
key={key}
data-emotion={`${key} ${ids.join(" ")}`}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: css }}
/>
))}
</head>
<body>
{children}
<ScrollRestoration />
<Scripts />
{process.env.NODE_ENV === "development" && <LiveReload />}
</body>
</html>
);
}
);

export default function App() {
return (
<Document>
<Outlet />
</Document>
);
}

export function CatchBoundary() {
const caught = useCatch();

return (
<Document title={`${caught.status} ${caught.statusText}`}>
<Container>
<p>
[CatchBoundary]: {caught.status} {caught.statusText}
</p>
</Container>
</Document>
);
}

export function ErrorBoundary({ error }: { error: Error }) {
return (
<Document title="Error!">
<Container>
<p>[ErrorBoundary]: There was an error: {error.message}</p>
</Container>
</Document>
);
}
24 changes: 24 additions & 0 deletions examples/emotion/app/routes/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import styled from "@emotion/styled";
import { Link } from "remix";

const Container = styled("div")`
font-family: "system-ui, sans-serif";
line-height: 1.4;
background-color: #ddd;
`;

export default function Index() {
return (
<Container>
<h1>Welcome to Remix with Emotion Example</h1>
<ul>
<li>
<Link to="/jokes">Jokes</Link>
</li>
<li>
<Link to="/jokes-error">Jokes: Error</Link>
</li>
</ul>
</Container>
);
}
3 changes: 3 additions & 0 deletions examples/emotion/app/routes/jokes-error.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function JokesError() {
throw new Error("This route is no joking with us.");
}
16 changes: 16 additions & 0 deletions examples/emotion/app/routes/jokes.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Link } from "remix";
import styled from "@emotion/styled";

const Container = styled("div")`
background-color: #d6d6d6;
`;

export default function Jokes() {
return (
<Container>
<h1>Jokes</h1>
<p>This route works fine.</p>
<Link to="/">Back to home</Link>
</Container>
);
}
11 changes: 11 additions & 0 deletions examples/emotion/app/styles/client.context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { createContext } from "react";

export interface ClientStyleContextData {
reset: () => void;
}

const ClientStyleContext = createContext<ClientStyleContextData>({
reset: () => {}
});

export default ClientStyleContext;
5 changes: 5 additions & 0 deletions examples/emotion/app/styles/createEmotionCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import createCache from "@emotion/cache";

export default function createEmotionCache() {
return createCache({ key: "remix-css" });
}
11 changes: 11 additions & 0 deletions examples/emotion/app/styles/server.context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { createContext } from "react";

export interface ServerStyleContextData {
key: string;
ids: Array<string>;
css: string;
}

const ServerStyleContext = createContext<null | ServerStyleContextData[]>(null);

export default ServerStyleContext;
Loading