The initial render of Next.js is not properly loading the CSS files

Encountering an issue with the initial load of the mobile app version; it seems that the CSS of my component covering the page is not loading correctly on the first screen load. However, when resizing to desktop and then switching back to mobile view, the styles display properly. I have observed that modifying the ID "__next" ensures that the desired styles remain on the page. However, the logic to check if the screen size is that of a mobile device in order to display a different icon is not working as expected. Refer to the images below for further clarification:

Without __next fix

With __next fix

Resize from desktop without fix

_document.tsx

/* eslint-disable @next/next/no-sync-scripts */
import React from 'react'
import Document, { Html, Main, NextScript, Head, DocumentContext } from 'next/document'

class CustomDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  };

  render() {
    return (
      <Html lang="pt-br" id="html">
        <Head>
          <link rel="preconnect" href="https://fonts.googleapis.com"/>
          <link rel="preconnect" href="https://fonts.gstatic.com"/>
          <link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png" />
          <link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png" />
          <link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png" />
          <link rel="icon" type="image/png" href="/favicon/favicon.ico" />
          <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet"/>
          <link rel="stylesheet" href="node_modules/react-github-contribution-calendar/default.css" type="text/css" />
          <script src="https://kit.fontawesome.com/1e2ddc5739.js"></script>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default CustomDocument

_app.tsx

import Head from 'next/head';
import { AuthProvider } from '../utils/contexts/AuthContext';
import GlobalStyle from '@/components/ui/styles/globalStyles';
import CssBaseline from '@mui/material/CssBaseline';

import { CacheProvider } from '@emotion/react';
import { createEmotionCache } from '@/utils/createEmotionCache';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { ModalProvider } from '@/utils/contexts/ModalContext';
import { ptBR } from '@mui/x-date-pickers/locales';
import { pt } from 'date-fns/locale'
import { RecoilRoot } from 'recoil';

const clientSideEmotionCache = createEmotionCache();

interface CustomAppProps {
  Component: any;
  pageProps: any;
  emotionCache: any;
}

const App = ({ Component, pageProps, emotionCache = clientSideEmotionCache }: CustomAppProps) => {
  const getLayout = Component.getLayout ?? ((page: any) => page);
  const locale = ptBR.components.MuiLocalizationProvider.defaultProps.localeText;
  return (
    <RecoilRoot>
      <AuthProvider>
        <CacheProvider value={emotionCache}>
          <LocalizationProvider dateAdapter={AdapterDateFns} localeText={locale} adapterLocale={pt}>
            <ModalProvider>
              <Head>
                <title>
                  Blakbelt
                </title>
                <meta
                  name="viewport"
                  content="initial-scale=1, width=device-width"
                />
              </Head>
              <CssBaseline />
              <GlobalStyle />
              <ToastContainer />
              {getLayout(<Component {...pageProps} />)}
            </ModalProvider>
          </LocalizationProvider>
        </CacheProvider>
      </AuthProvider>
    </RecoilRoot>
  );
};

export default App;

Answer №1

Ensure that your global styles are SSR-compatible when implementing them. To apply styles exclusively for the client-side, consider leveraging next/dynamic to dynamically load them.

For instance:

import dynamic from 'next/dynamic';

const ClientSpecificStyles = dynamic(() =>
  import ('../path/to/client-specific-styles.css'), {
    ssr: false,
  });

Answer №2

Here is the code snippet that you can implement in your Component file.

<style jsx>{`
//add your styles here
`}
</style>

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

Tips for transmitting form information in a fetch call

As I was developing a nodejs server, I encountered an issue with the POST call that involves sending form input data to a remote server. Despite everything else working fine, the form data was not being received by the server. Below is the code snippet in ...

Tips for connecting a Django API project with a nodejs and react frontend

I'm currently working on a Django API project and I am considering incorporating Node.js into the mix. Additionally, I am interested in using React for the frontend of the application. Is this combination of technologies feasible? Would it be advisabl ...

Conceal the cursor within a NodeJS blessed application

I am struggling to hide the cursor in my app. I have attempted various methods like: cursor: { color: "black", blink: false, artificial: true, }, I even tried using the following code inside the screen object, but it didn't work: v ...

Removing extra spaces from a hyperlink using CSS

Can CSS be used to remove extra whitespaces? Within the code snippet provided, there is an additional whitespace in the <a> tag. This link is generated by a WordPress plugin and I prefer not to make changes directly to the source files of the plugin. ...

Explore the world of HTML event listening through .NET integration

Imagine this scenario: within an HTML page, using an UpdatePanel, you have a loading animated gif spinning while ASP.NET processes data from a webservice. I'm curious if there's a way to create an Event in .NET code that can be detected on the H ...

Switch the paper tab to a dropdown menu in Polymer.js

Can someone assist me in transforming the paper tab into a paper drop down menu in polymer JS? I want the drop-down to appear with a list of values when hovering over the Top menu. Activity Execution <paper-tab cla ...

centralize the tracking of all user interactions within a React application

In React, I am looking for a way to centrally capture user interactions such as clicks, scrolls, and more. Is there a listener or similar mechanism that can capture all these events in one place without needing to write code in each individual component? ...

Issue - Unrecognized listen EADDRINUSE :::5432 detected in Windows Command Prompt

I encountered an issue when I tried running gulp serve --nobrowser, resulting in the following error: { Error: listen EADDRINUSE :::5432 at Object._errnoException (util.js:992:11) at _exceptionWithHostPort (util.js:1014:20) at Server.setupListenHandle [as ...

Deactivate input areas while choosing an option from a dropdown menu in HTML

I've been working on creating a form and have everything set up so far. However, I'm looking to disable certain fields when selecting an option from a dropdown list. For instance, if the "within company" option is selected for my transaction typ ...

Incorporating Stripe into your Next.js 13 application: A step-by-step guide

Struggling to incorporate Stripe into my Next.js 13 app for a pre-built checkout form. So far, all attempts have fallen short. Seeking assistance from anyone who has conquered this integration successfully. Any tips or guidance would be highly valued. Pl ...

The sass compiler has produced two separate CSS files, but I am only able to link one of them to the index.html file

Everything was going smoothly with my SASS compiler. The styles were reacting perfectly in the live web server. But then, out of nowhere, it stopped working. Upon closer inspection, I realized that the extension had created a new CSS file. Instead of compi ...

JavaScript callbacks are not executed synchronously

My Objective : I am attempting to initiate a payment order in the payment gateway server and then send back the order details to the client using Firebase cloud functions. This process involves utilizing firebase cloud functions. The Order() function ha ...

Positioning an Element on a Web Page in Real-Time

Trying to implement an Emoji picker in my React application, I have two toggle buttons on the page to show the picker. I want it to appear where the Toggle button is clicked - whether at the top or bottom of the page. The challenge is to ensure that the pi ...

Deployment on Vercel with Next.js does not execute the codegen command

Encountering a module not found error for imported generated types with codegen during Vercel build of my React Next.js project using Typescript and pnpm. On the development server, I manually generate types by running 'pnpm gen' command in the t ...

The relationship between two distinct servers: Express.js and Node.js

Working with the Express.js framework and Node.js, I am trying to make a request to an MS SQL database on the server side. My goal is to retrieve data (in JSON or array format) from the server and send it to the client side. I'm unsure about how to ...

Arrange four Divs next to each other with flexbox styling

I've been struggling with aligning my cards side by side. They are a series of divs nested in lists under a <ul> Changing the positioning is not resolving the issue, and I'm hesitant to alter the display as it's crucial for responsive ...

Having difficulty constructing a full stack application using Express

I've been struggling to configure a full stack app using create-react-app with Express and TypeScript. My main issue is figuring out how to compile the server files into a build folder. I have separate tsconfig files for the server and create-react-ap ...

Tips for efficiently transferring a retrieved object from App.js to a child component in ReactJS version 16 and above using asynchronous methods

TL;DR How can I pass a fetched object from App.js to a child component asynchronously? Do I need to wait for the data to be completely fetched before returning App.js? If so, how can I achieve this? In an attempt to create a dashboard using react-chartj ...

The process of loading the Facebook like script using $.getScript is causing an issue where the

How can I make the Facebook like button display properly on my HTML page? I have successfully loaded scripts and divs for Twitter, Google +1 buttons, but the Facebook like button script is not displaying the button. The alert shows that the script is exec ...

Node.js application with decoupled Redis client

In my node.js app, I am utilizing Redis for user caching. Once a user logs in, their information is cached and accessed on subsequent requests to determine their access level. This allows the client to receive personalized information and views based on th ...