I encountered an issue while attempting to load Google Fonts. I came across a solution that suggests adding the following code snippet in _document.js
to import it within a head tag:
import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
<link
rel="preload"
href="/fonts/noto-sans-v9-latin-regular.woff2"
as="font"
crossOrigin=""
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
However, this approach conflicted with the code required to enable Styled Components in Next.js:
import Document, { DocumentContext } from 'next/document';
import { ServerStyleSheet } from 'styled-components';
export default class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
};
} finally {
sheet.seal();
}
}
}
Therefore, my query is: how can I adjust my _document.js
file to incorporate the styles from Google Fonts?
Additionally, here is the GlobalStyle I am utilizing which does not include the imported fonts:
import { createGlobalStyle } from '@xstyled/styled-components';
const GlobalStyle = createGlobalStyle`
@import url('https://fonts.googleapis.com/css2?family=Lato&family=Rubik&display=swap');
* {
margin: 0;
padding: 0;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
html {
box-sizing: border-box;
font-size: 62.5%;
position: relative;
background: grey;
}
body {
font-family: 'Lato', sans-serif;
}
`;
const BasicLayout = ({ children }: { children: any }) => {
return (
<>
<GlobalStyle />
{children}
</>
);
};
export default BasicLayout;