Skip to content

Instantly share code, notes, and snippets.

@LeeCheneler
Created March 4, 2023 17:21
Show Gist options
  • Save LeeCheneler/4d976ba0049002a80cc7b9bc6ad8828f to your computer and use it in GitHub Desktop.
Save LeeCheneler/4d976ba0049002a80cc7b9bc6ad8828f to your computer and use it in GitHub Desktop.
Mantine working with Next 13 app dir
"use client";
import React from "react";
import { CacheProvider } from "@emotion/react";
import createCache from "@emotion/cache";
import { MantineProvider } from "@mantine/core";
import { defaultTheme } from "@opsnoir/mantine-theme";
import { useServerInsertedHTML } from "next/navigation";
import { trpc } from "../utils/trpc";
// emotion next 13 app directory support
// https://github.com/emotion-js/emotion/issues/2928#issuecomment-1319747902
const useConfigureEmotion = () => {
const [{ cache, flush }] = React.useState(() => {
const cache = createCache({ key: "emotion" });
cache.compat = true;
const prevInsert = cache.insert;
let inserted: string[] = [];
cache.insert = (...args) => {
const serialized = args[1];
if (cache.inserted[serialized.name] === undefined) {
inserted.push(serialized.name);
}
return prevInsert(...args);
};
const flush = () => {
const prevInserted = inserted;
inserted = [];
return prevInserted;
};
return { cache, flush };
});
useServerInsertedHTML(() => {
const names = flush();
if (names.length === 0) {
return null;
}
const styles = names.map((name) => cache.inserted[name]).join("");
return (
<style
key={cache.key}
data-emotion={`${cache.key} ${names.join(" ")}`}
dangerouslySetInnerHTML={{
__html: styles,
}}
/>
);
});
return { emotionCache: cache };
};
interface ProvidersProps {
children: React.ReactNode;
}
export const Providers = (props: ProvidersProps) => {
const { emotionCache } = useConfigureEmotion();
return (
<CacheProvider value={emotionCache}>
<MantineProvider withGlobalStyles withNormalizeCSS theme={defaultTheme} emotionCache={emotionCache}>
{props.children}
</MantineProvider>
</CacheProvider>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment