简体   繁体   中英

Next.js 13 with Ant Design 5: Components and Pages Render Before Styles Load, Causing Jump

I followed the antd and nextjs doc to config the project.

Added this code into the ./scripts/genAntdCss.tsx file:

import { extractStyle } from '@ant-design/static-style-extract';
import fs from 'fs';
const outputPath = './public/antd.min.css';
const css = extractStyle();
fs.writeFileSync(outputPath, css);

and this is App.tsx file:

import { StyleProvider } from '@ant-design/cssinjs';
import type { AppProps } from 'next/app';
import '../public/antd.min.css';

export default function App({ Component, pageProps }: AppProps) {
  return (
    <StyleProvider hashPriority='high'>
      <Component {...pageProps} />
    </StyleProvider>
  );
}

these commands added to package.json file:

"predev": "ts-node --project ./tsconfig.node.json ./scripts/genAntdCss.tsx",
"prebuild": "ts-node --project ./tsconfig.node.json ./scripts/genAntdCss.tsx"

Do you have any idea to fix this?

I found a way to solve it but I had to use the new "app", "layout" and "use client" features of NextJS 13. I hope it helps someone:

I answered here but I will copy and paste it here again to avoid you from opening it: https://github.com/ant-design/ant-design/issues/38555#issuecomment-1535788843

Well, I've found the link below where @chunsch added an example in the NextJS repo https://github.com/vercel/next.js/pull/44015/files

Also, @kiner-tang helped us to fix the layout shift while loading https://github.com/ant-design/ant-design/issues/42275#issuecomment-1555805914

It's possible but we need to do some weird stuff with the new cssinjs AntD 5 feature and with the NextJS 13 app and layout features. I would like to avoid using that but it's the way I found. Sorry.

I basically had to use the new "app" directory (experimental feature yet), create a root layout (layouts are one of the new features too), and create a RootStyleRegistry component specifying that it should be a client component with the 'use client' directive. Additionally, if you use the Layout component, you should specify the hasSider={true} prop to avoid a shifting effect in the first render.

Install @ant-design/cssinjs if you don't have it installed

  1. Create the RootStyleRegistry component
// located at src/modules/shared/components/root-style-registry/index.tsx in my case

'use client'
import { useState, type PropsWithChildren } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { createCache, extractStyle, StyleProvider } from '@ant-design/cssinjs'

export const RootStyleRegistry = ({ children }: PropsWithChildren) => {
  const [cache] = useState(() => createCache())

  useServerInsertedHTML(() => {
    return (
      <script
        dangerouslySetInnerHTML={{
          __html: `</script>${extractStyle(cache)}<script>`,
        }}
      />
    )
  })

  return <StyleProvider cache={cache}>{children}</StyleProvider>
}

  1. Create the layout for the root page
// src/app/layout.tsx
import type { PropsWithChildren } from 'react'
import { RootStyleRegistry } from '../modules/shared/components/root-style-registry'

export default function RootLayout({ children }: PropsWithChildren) {
  return (
    <html lang="es">
      <head />
      <body>
        <RootStyleRegistry>{children}</RootStyleRegistry>
      </body>
    </html>
  )
};

  1. Create your page component using the 'use client' directive. Remember you must name it 'page' now (like an index file inside a folder)
// src/app/page.tsx

'use client'
import React, { Button, Card, Space, Typography } from 'antd'

export default function Home() {
  return  <Button type="primary">Ant Design Button</Button>
}

  1. If you use the Layout component and you are experimenting a navbar shift while loading, you should explicitly specify the 'hasSider' prop
// src/app/components/layout.tsx

export function MyLayout({ children }) {
  return (
    <Layout hasSider>
      <Sider>
        {children}
      </Sider>
    </Layout>
  )
}

It worked for me following the instructions in the AntD docs, which it looks like you're doing.

https://ant.design/docs/react/customize-theme#server-side-render-ssr

Make sure you are installing the necessary dependencies

npm install ts-node tslib --save-dev

and adding the tsconfig.node.json , you didn't specify that you did these two steps.

https://mobile.ant.design/guide/ssr

// next.config.js
const nextConfig = {
  transpilePackages: ['antd-mobile'], // or ['antd']
};

module.exports = nextConfig;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM