I'm using global style from styled components with next.js and every time I reload my page I can see the font flickering.
I have my font files in public/fonts/Inconsolata
I've looked everywhere in spectrum chat, next.js github issues but can't seem to find any solution.
pages/index.js
import styled from 'styled-components';
const H1 = styled.h1`
font-family: 'Inconsolata Bold';
font-weight: 700;
color: #000;
`;
const index = () => {
return (
<div>
<H1>font flashes</H1>
</div>
);
};
export default index;
pages/_app.js
import App from 'next/app';
import React from 'react';
import GlobalStyle from '../src/style/globalStyle';
export default class MyApp extends App {
render() {
const { Component, pageProps } = this.props;
return (
<>
<GlobalStyle />
<Component {...pageProps} />
</>
);
}
}
pages/_document.js
import Document from 'next/document';
import { ServerStyleSheet } from 'styled-components';
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
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();
}
}
}
style/globalStyle.js
import { createGlobalStyle } from 'styled-components';
const globalStyle = createGlobalStyle`
@font-face {
font-family: 'Inconsolata';
src: url('./fonts/Inconsolata/Inconsolata-Regular.woff2') format('woff2'),
url('./fonts/Inconsolata/Inconsolata-Regular.woff') format('woff');
font-weight: 400;
font-style: normal;
font-display: fallback;
}
@font-face {
font-family: 'Inconsolata Bold';
src: url('./fonts/Inconsolata/Inconsolata-Bold.woff2') format('woff2'),
url('./fonts/Inconsolata/Inconsolata-Bold.woff') format('woff');
font-weight: 700;
font-style: bold;
font-display: fallback;
}
`;
export default globalStyle;