Add StyleProvider cache to fix page load issues

This commit is contained in:
Muaz Ahmad 2024-06-07 13:08:28 +05:00
parent 0fbbe124d6
commit a266fdaaeb

View File

@ -1,7 +1,9 @@
/* eslint-disable react/no-danger */
import { readFileSync } from 'fs';
import { join } from 'path';
import { Html, Head, Main, NextScript } from 'next/document';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import type { DocumentContext } from 'next/document';
import { createCache, extractStyle, StyleProvider } from '@ant-design/cssinjs';
class InlineStylesHead extends Head {
getCssLinks: Head['getCssLinks'] = ({ allFiles }) => {
@ -22,14 +24,46 @@ class InlineStylesHead extends Head {
};
}
export default function Document() {
return (
<Html lang="en">
<InlineStylesHead />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
const Doc = () => (
<Html lang="en">
<InlineStylesHead />
<body>
<Main />
<NextScript />
</body>
</Html>
);
/*
Yoinked from https://ant.design/docs/react/use-with-next#using-pages-router. Change if someone figures out a way to
mesh this with the InlineStyles above.
*/
Doc.getInitialProps = async (ctx: DocumentContext) => {
const cache = createCache();
const originalRenderPage = ctx.renderPage;
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => props => (
<StyleProvider cache={cache}>
<App {...props} />
</StyleProvider>
),
});
const initialProps = await Document.getInitialProps(ctx);
const style = extractStyle(cache, true);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
<style dangerouslySetInnerHTML={{ __html: style }} />
</>
),
};
};
export default Doc;