Antd CSS application is experiencing a delay

Upon refreshing the page on Next.js with Antd CSS, I am experiencing a delay in applying the styles. The content appears misaligned right after the reload. Is there a way to fix this issue?

I suspect it may be related to SSR, but unfortunately, I have not been able to find a solution.

  • next.js: 13
  • antd: 5

Answer №1

You have the ability to establish a context at the root of your application that displays a loading indicator until all processes such as computation and data fetching are complete, at which point you can hide the loading indicator.

Here is an example implementation:

// mycontext.ts

import React, {
  useState,
  createContext,
  useMemo,
  useContext
} from 'react'
import {
  Spin
} from 'antd'

type ContextType = {
  loading: boolean
  setLoading: React.Dispatch<React.SetStateAction<boolean>>
}

const MyContext = createContext( {} as ContextType )

export function ContextProvider({children}) {
  const [loading, setLoading] = useState<boolean>(true)

  return (
    <MyContext.Provider
      value={useMemo(() => ({
        loading, setLoading
      }), [loading])}
    >
      <Spin spinning={loading}>
        {children}
      </Spin>
    </MyContext.Provider>
  )
}

export function useMyContext {
  return useContext(MyContext)
}

To incorporate this context in the entry point of your app (_app.tsx):

import {ContextProvider} from 'path/to/context'
import {
  App,
  ConfigProvider
} from 'antd'

function _app({
  Component,
  pageProps
}: AppProps) {
  return (
    <ConfigProvider
        locale={ ... }
        theme={ ... }
    >
      <App>
        <ContextProvider { ...pageProps }>
          <Component { ...pageProps } />
        </ContextProvider>
      </App>
    </ConfigProvider>
  )
}

In individual components, you can also manage the visibility of the loading indicator within this context:

// anycomponent.tsx

import {useMyContext} from 'path/to/context'

function MyComponent() {
  const {loading, setLoading} = useMyContext()

  ....
}

Answer №2

generate a file in this format.

"use client";

import { StyleProvider, createCache, extractStyle } from "@ant-design/cssinjs";
import { useServerInsertedHTML } from "next/navigation";
import React from "react";
const StyledComponentsRegistry = ({ children }: { children: React.ReactNode }) => {
  const cache = createCache();
  useServerInsertedHTML(() => <style id="antd" dangerouslySetInnerHTML={{ __html: extractStyle(cache, true) }} />);

  const render = <>{children}</>;

  if (typeof window !== "undefined") {
    return render;
  }

  return (
    <StyleProvider hashPriority="high" cache={cache}>
      {children}
    </StyleProvider>
  );
};

export default StyledComponentsRegistry;

and enclose it within the main layout document

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body className="bg-gray-200">
                  <StyledComponentsRegistry>{children}</StyledComponentsRegistry>
      </body>
    </html>
  );
}

This method was successful for me. If it doesn't work for you, consider updating the packages

Answer №3

Ensure you make the necessary changes in your _document.tsx file

import Document, { Html, Head, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class CustomDocument 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()
    }
  }
  render() {
    return (
      <Html>
        <Head>
          <link rel="icon" href="/favicon.ico" />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

For more information, check out this helpful Link

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

Exploring the implementation of constructors and classes in JavaScript

I have a task to create a class named ShoppingCart with specific instructions: The class should have a constructor that initializes the total attribute to zero and creates an empty dictionary attribute called items. There should be a method named add_ite ...

Creating a chart in React using vanilla JavaScript: A step-by-step guide

exampleFunction = () => { return ( <div> <canvas class="myChart"></canvas> </div> ) } What is the best way to incorporate JavaScript code into the <script>js code</script> for the myChart ...

Experiencing difficulty importing Materialize CSS JS into React

Good day everyone, I've been facing challenges in implementing materialize css into my react-app, specifically with the JavaScript files. After trying various methods, I believe that I have made some progress using the following approach: In my &ap ...

Utilizing the 'use server' behavior in Next.js Server Component without explicit declaration

When utilizing the Server Component feature in Next.js, it is necessary to declare either 'use client' or 'use server' at the start of the jsx file. The default processing method is 'use server', so including it explicitly may ...

What is the method to prevent the label from closing in the MUI 5 datepicker?

Is there a method to prevent the Material 5 Datepicker from closing when there's a label but no value? Current Scenario: Current Desired Outcome: Expected Sample Code: <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker lab ...

How to efficiently pass props between components in NextJs

This is the project's file structure: components ├─homepage │ ├─index.jsx ├─location │ ├─index.jsx pages │ ├─location │ │ ├─[id].jsx │ ├─presentation │ │ ├─[id].jsx │ ├─_app.jsx │ ├─index.jsx ...

The value of type 'string' cannot be assigned to type '"menu" | "selectedMenu" | undefined' as it is not compatible with the specified types

I'm working on creating a multiple select feature using TypeScript, material-ui, and React. I am encountering an error when trying to set MenuProps.variant = 'menu'. The error message reads: "Type '{ variant: string; PaperProps: { styl ...

Is there a way to modify the characteristics of a specific dependency?

I'm currently in the process of learning how to use the npm library, and came across this carousel. I successfully integrated it into my project, but now I find myself unsure about modifying its attributes. For reference, here's the documentation ...

The React DOM isn't updating even after the array property state has changed

This particular issue may be a common one for most, but I have exhausted all my options and that's why I am seeking help here. Within my React application, I have a functional component named App. The App component begins as follows: function App() ...

Server Functions and Documents

Is it viable to utilize server actions for file uploads in a Next.js project, such as storing images, documents, spreadsheets, and PDFs in the public folder? While Node.js offers options like Multer and Formidable for this purpose, I am faced with challen ...

What is the best way to hold off displaying the entire component until the image inside has finished loading?

One of my components includes an image that loads after the page content. How can I delay rendering the entire component until the image has fully loaded? I attempted wrapping the containing div (id="container") in a Suspense component with a fallback met ...

Error in React Bootstrap: ReferenceError - 'openModal' is not defined

Whenever the button is clicked, my intention is for a modal to open. I have written the code for it, but I'm encountering errors that I can't seem to resolve. Here's the snippet of my code: import React from "react"; import { M ...

Is it necessary to bring in CSS for the following page?

Should CSS be imported and used across multiple pages in a web application? Is the page structure outlined below considered acceptable, or is there a standard practice to follow? /pages /home index.js index.module.css /cart ...

Why is the exit animation malfunctioning in Next.js with Framer Motion?

My application is built using next js and I am incorporating framer motion for animations. The introductory animation works fine, but I am unable to get any of the exit animations to function. I have enclosed the code within animated presence, however, it ...

How to resolve undefined callback when passing it to a custom hook in React Native

I'm facing an issue with passing a callback to my custom hook: export default function useScreenshotDetection(onScreenshot) { useEffect(() => { ... onScreenshot(); ... }, []); } Strangely, the callback is not being detected ...

Looking to update the date in 'React Fullcalendar' using a 'drop-down' filter. How can this be accomplished?

Is there a way to change the viewing date of a component using a 'DropDown' filter? I've seen plenty of answers about changing views, but nothing specifically on changing dates T^T Can anyone provide some helpful insights on this topic? ...

Issue with React-Toastify not displaying on the screen

After updating from React-Toastify version 7.0.3 to 9.0.3, I encountered an issue where notifications are not rendering at all. Here are the steps I followed: yarn add [email protected] Modified Notification file import React from "react" ...

What steps do I need to take in order to modify information within a table using Symfony?

Working on my Symfony project, I frequently need to display various views in table format. I wish I could easily update the data by clicking on table cells, entering new information, and saving it dynamically. After exploring jqGrid, DataTable with jEdit ...

Ending a Firestore `get` query upon unmounting component

Currently, I am retrieving data from Firestore in the componentDidMount function. However, if I happen to change the component while it is still in the process of fetching data, an error occurs: Warning: Can't call setState (or forceUpdate) on an u ...

Creating a nested or indented text list with MUI Typography is a breeze!

In my current setup, the data structure looks like this: const bullets = [ "Top Sports are:", "hockey", "soccer", "football", "Top Names are:", "liam", "noah", "jordan" ] Usin ...