Caution: The prop `className` did not align when utilizing @font-face alongside styled-components in NextJS

https://i.stack.imgur.com/ZLtue.png

Greetings, everyone. I've recently crafted a GlobalStyle in which I'm defining my fonts using font-face.

import { createGlobalStyle } from 'styled-components';

export const GlobalStyle = createGlobalStyle`
body {
    font-family: 'Roboto', sans-serif;
}
  html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font-family: 'Roboto', sans-serif;
    vertical-align: baseline;
}
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}
@font-face {
  font-family: "Roboto";
  src: url("/fonts/Roboto/Roboto-Regular.ttf");
  font-style: normal;
  font-weight: 400;
  font-display: swap;
}
@font-face {
  font-family: "Roboto";
  src: url("/fonts/Roboto/Roboto-Bold.ttf");
  font-style: bold;
  font-weight: 700;
  font-display: swap;
}
`;

This GlobalStyle gets called within my _app.tsx file. The fonts are stored in the public directory.

I haven't encountered this error before, but it arose once I introduced the @font-face declaration.

Here's what I've attempted:

Adding this snippet to .babelrc:

"plugins": [["styled-components", { "ssr": true }]]

Installing extensions like babel-preset-next and babel-plugin-styled-components.

Despite these efforts, nothing has resolved the issue. What am I overlooking?

styled-components version: 5.3.0 next: 11.0.1

Answer №1

Solved the issue by adding a _document.tsx file inside the pages folder.

import Document from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class CustomDocument extends Document {
  static async getInitialProps(ctx: any) {
    const stylesSheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App: any) => (props: any) =>
            stylesSheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {stylesSheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      stylesSheet.seal();
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving data from the database using getStaticProps in Next.js

As I was following a tutorial on Next.js, the instructor did something that deviated from what I had learned in school and left me pondering. Here is what he did: interface FaqProps { faq: FaqModel[]; } export default function Faq({ faq }: FaqProps) { ...

Hazy placeholder in Material UI Select alongside the selected value

In the code snippet below, you can see my Select component. I've implemented a data fetching process and within the useEffect, I am setting the categoryId. However, an issue arises where the placeholder is displayed in the background as shown in this ...

What is the best way to assign a background image to a div in React Js?

Is there a way to set an image as the background of a div in React without using a const? I need the image to serve as a background image so that I can overlay text on top of it. I am looking for a solution that doesn't involve hardcoding the backgr ...

React Native: Image display issue

I'm facing a problem with displaying an image. I've followed all the steps correctly as per a tutorial, but for some reason, my image is not showing up while the author's images are displayed perfectly. What could be causing this issue? I ha ...

The React application encountered an error while trying to read properties of undefined, specifically the 'map' property

Having trouble running this code in React. Any suggestions on how to fix it? return ( <div className="container my-4"> <h1>News Monkey - Top Headlines</h1> <div className="row" ...

Struggling with getting React to successfully fetch data from an Express API. Any suggestions on how

I am having trouble with my fetch call to the express API. Even though I receive a response status of 200, I am still getting the index.html instead of the JSON data I need. Here is an overview of my setup: package.json "version": "1.0.0&qu ...

Problem with prompt updating when the input value is modified in the text field

My application depends on the 'city' value to make an API call and fetch data. To achieve this, I have set up a form that utilizes a setState value for my city and a useEffect value in my main App.js file so that each time a new city is submitted ...

Receiving an eslint error while trying to integrate Stripe pricing table into a React web application

If you're looking to incorporate a Stripe documentation code snippet for adding a stripe-pricing-table element, here's what they suggest: import * as React from 'react'; // If you're using TypeScript, don't forget to include ...

AWS Amplify is not displaying images correctly, although they are functioning properly in development mode

I am facing an issue with my Next.js project deployed on AWS Amplify. While images load properly in development mode, they are not loading in production mode. I have tried various solutions such as: Enabling the "Legacy cache settings" option and setting ...

Unraveling the Power of Recursive Functions within a React.JS

I'm encountering an issue with a React project. It involves a tic tac toe game where I'm currently working on the implementation of the computer player. The problem arises when the human player clicks on one square (Field-component), triggering ...

Switch up the like button for users who have previously liked a post

Greetings, I trust everything is going well. I am attempting to implement a feature where users can like a post or article created by others using a button. I have established a const function named "getAPostLikeRecord()," which retrieves a list of users w ...

This error message 'React Native _this2.refs.myinput.focus is not a function' indicates that

When working with React-Native, I encountered a specific issue involving a custom component that extends from TextInput. The code snippet below demonstrates the relevant components: TextBox.js ... render() { return ( <TextInput {...this.props} ...

Unable to modify the theme provider in Styled Components

Currently, I am attempting to customize the interface of the PancakeSwap exchange by forking it from GitHub. However, I have encountered difficulties in modifying not only the header nav panel but also around 80% of the other React TypeScript components. ...

I am encountering an issue where the props in NextJS consistently return as undefined

I am currently working on setting up a connection with Contentful. The connection itself seems to be functioning properly and is not the issue, however, when I attempt to transfer the data using props, I keep receiving 'undefined'. I have simpli ...

When an input element is being controlled from outside the modal using a portal, it is losing focus after a key press

[Resolved] The input component is experiencing a focus issue when any key is pressed, only when its value is controlled from outside of the portal. NOTE: I apologize for any confusion. While writing this post, I identified the problem in my code, but dec ...

Can a JWT token be verified without access to the secret key?

Recently, my focus has been on understanding JWT and its potential application. I have been exploring the idea of incorporating JWT into a Next.js server alongside an external authentication server that issues JWT access tokens. Initially, I considered th ...

Unexpectedly, the image has ceased to load

I have been working on a project called decentragram. Everything was functioning properly a few days ago, but now the images are not loading. I am getting an error message that says: bafybeieq6nyhu7ilorb7dxepo6sexab6oqigkjhzc62dxio6x5xaurge7u.ipfs.infura-i ...

Utilizing shared components across a Next.js application within a monorepo

Utilizing a monorepo to share types, DTOs, and other isomorphic app components from backend services (Nest.js) within the same mono repo has presented some challenges for me. In my setup, both the next.js app and nest.js app (which itself is a nest.js mono ...

Creating a dynamic route that redirects to the same page using Nextjs

What should I do if I have 2 links that both lead to the same page? First link: '/:language/:type/:name' ("en/doctor/balestra") Second link: '/:type/:name' ("doctor/balestra") If not specified, the language will default to "en" I at ...

What is the best way to extract a nested array of objects and merge them into the main array?

I've been working on a feature that involves grouping and ungrouping items. A few days ago, I posted this question: How can I group specific items within an object in the same array and delete them from the core array? where some helpful individuals ...