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

https://i.sstatic.net/S2sHU.png

With __next fix

https://i.sstatic.net/4pxzS.png

Resize from desktop without fix

https://i.sstatic.net/5NtlH.png

_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

The jQuery response appears blank in the browser, despite the fact that it works fine with

Utilizing jQuery's .ajax() function to communicate with a local Django runserver and retrieve a response. Observing the server console, the JSON request is received properly, a correct JSON response is generated, and all appears in order. However, i ...

Mastering the art of invoking a JavaScript function from a GridView Selected Index Changed event

In my current setup where I have a User Control within an Aspx Page and using Master Page, there's a GridView in the User Control. My goal is to trigger a javascript function when the "Select" linkbutton on the Gridview is clicked. Initially, I succe ...

Leveraging ng-transclude and the require attribute for effective communication between directives

I'm working with two directives, let's call them: angular.module('app').directive('directiveX', directiveX); function directiveX(){ return { restrict: 'E', transclude: true, ...

Is there a way to encompass the entire application within a Middleware in Next JS 13?

My approach has been to encapsulate the entire application within a middleware, based on what the documentation states: export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) ...

Styling the navigation bar using CSS and positioning a <div> element underneath

Struggling to design a navbar using Bootstrap and have a div positioned underneath it that fills the remainder of the page? You're not alone! As someone new to Bootstrap and CSS, this can be tricky. Here's an example of how I created a navbar: ...

Is there a way to capture and monitor all page traffic within a scrollable website using playwright?

Here is the code I am using: import { firefox } from 'playwright'; // domain let domain = 'https://www.reddit.com/' // create a new page const page = await browser.newPage(); // set routes await page.route('**', async route = ...

Tips for rendering a server-side component within a client-side component in a React 18 - Next.js 14 application router

As outlined in this RFC: Server Components or call server hooks/utilities cannot be imported by Client Components, as they are specific to server functionality. Currently, I am developing a project using react v18.2 and nextjs v14 with app router integr ...

Preventing mouse clicks on checkboxes and triggering events using JavaScript - a complete guide

We have a Table grid with multiple columns, one of which is a Select Box (CheckBox). The expected behavior is that when a row is clicked, the respective CheckBox should get checked, and clicking on the CheckBox itself should update it. I tried implementin ...

The date-picker element cannot be selected by html2canvas

I'm encountering an issue with Html2canvas while trying to capture a screenshot of my page. Specifically, the date shown in the date-picker on the page is not appearing in the screenshot. Do you have any insights into why this might be happening and h ...

Ensure that the footer remains at the bottom of the webpage, without being positioned as fixed

I am encountering an issue on my work2 Website where the footer is not staying at the bottom of the page when there is limited content. I have searched extensively on Google, YouTube, and CSS tricks for a solution, but have not found one that works for my ...

Updating content with jQuery based on radio button selection

Looking for assistance with a simple jQuery code that will display different content when different radio buttons are clicked. Check out the code here. This is the HTML code: <label class="radio inline"> <input id="up_radio" type="radio" n ...

Having trouble getting custom Themes to apply in Material UI version 5

I meticulously followed the documentation to create a custom theme, but unfortunately, I'm not seeing any changes reflected in my UI. Both the primary and secondary colors remain the same as the default, despite my efforts. Additionally, the warning, ...

Ways to avoid the browser from storing a JSON file in its cache

Hey there, I'm working on a project and running into some issues with caching. The problem I'm facing is that the browser keeps holding onto the json file containing save data even after I update it elsewhere. This means that the browser is readi ...

Empty req.body in Express JS is not fulfilling the necessary data requirements

I've been racking my brain for hours trying to figure out why req.body is showing up empty. I've scoured every corner of stackoverflow and tried every solution that I could find, but nothing seems to be working. Express.js POST req.body empty ...

How can we properly access the DOM element generated by an {#each} loop in Svelte when it is clicked?

Using Svelte's {#each} functionality, I am reactively loading elements in the following way: {#each $items as item} <div> <Button on:click={someFunction}>{item.text}</Button> (*) </div> {/each} (*) a component t ...

What is the methodology behind incorporating enumerations in typescript?

I've been curious about how typescript compiles an enumeration into JavaScript code. To explore this, I decided to create the following example: enum Numbers { ONE, TWO, THREE } Upon compilation, it transformed into this: "use strict ...

Assessing the string to define the structure of the object

Currently, I am attempting to convert a list of strings into a literal object in Javascript. I initially tried using eval, but unfortunately it did not work for me - or perhaps I implemented it incorrectly. Here is my example list: var listOfTempData = [ ...

The React-player's default setting for Vimeo is to display the player in a compact size initially

I recently integrated the Reactplayer package into my Next.js application to load a Vimeo video. However, I noticed that during the initial render, the player appears small and then expands to its full size, similar to what is shown in the screenshot below ...

Issue: When trying to deploy my NextJS site to Vercel, I encountered an error with the command "yarn run build" exiting with the code 1. Any

I am currently trying to deploy my NextJS site to Vercel. Unfortunately, I seem to be encountering some errors that I'm unable to resolve on my own. Here is the Build Log for reference: Any assistance provided would be highly appreciated. Thank you ...

The ajax response is returning the entire page's html code instead of just the text content from the editor

I've been working with CKEditor and I'm using AJAX to send the editor's content via POST method. However, when I try to display the response in a div, the HTML for the entire page is being returned instead of just the editor's content. ...