DEV Community

Ahmad Faraz
Ahmad Faraz

Posted on

NextJs 14 with antd 5.11

Hello everyone,

Today I will guide you how we can implement antd in NextJs 14.

Recently I was working on a client project, there we are using NextJs 12 version and antd 4.20.2 version, I got a task, I have to update our NextJs version to 14, because our web app NextJs 12 was very slow and we have to upgrade the version.

There is a lot of fantastic updates in NextJs 14, you can see on this link

First I have a problem with antd because Ant Design's CSS is loading after the page is rendered, causing a flash of unstyled content in next Js 14. I searched a lot of articles but couldn't find anything right related to this.

I saw few updates in antd on antd documentation

Here is the steps, how we can implement antd in our NextJs 14 app.

Step 1:

npx create-next-app@latest
Enter fullscreen mode Exit fullscreen mode

Image description

Step 2:

npm install antd
Enter fullscreen mode Exit fullscreen mode

Step 3:

npm install @ant-design/cssinjs
Enter fullscreen mode Exit fullscreen mode

Step 4:

Create lib/AntdRegistry.tsx in your src directory

'use client';

import React from 'react';
import { createCache, extractStyle, StyleProvider } from '@ant-design/cssinjs';
import type Entity from '@ant-design/cssinjs/es/Cache';
import { useServerInsertedHTML } from 'next/navigation';

const StyledComponentsRegistry = ({ children }: React.PropsWithChildren) => {
  const cache = React.useMemo<Entity>(() => createCache(), []);
  const isServerInserted = React.useRef<boolean>(false);
  useServerInsertedHTML(() => {
    // avoid duplicate css insert
    if (isServerInserted.current) {
      return;
    }
    isServerInserted.current = true;
    return <style id="antd" dangerouslySetInnerHTML={{ __html: extractStyle(cache, true) }} />;
  });
  return <StyleProvider cache={cache}>{children}</StyleProvider>;
};

export default StyledComponentsRegistry;
Enter fullscreen mode Exit fullscreen mode

Step 5:

Update your layout.tsx file

import React from 'react';
import { Inter } from 'next/font/google';

import StyledComponentsRegistry from '../lib/AntdRegistry';

import '@/globals.css';

const inter = Inter({ subsets: ['latin'] });

export const metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
};

const RootLayout = ({ children }: React.PropsWithChildren) => (
  <html lang="en">
    <body className={inter.className}>
      <StyledComponentsRegistry>{children}</StyledComponentsRegistry>
    </body>
  </html>
);

export default RootLayout;
Enter fullscreen mode Exit fullscreen mode

NextJs documentation: https://nextjs.org/docs/app/building-your-application/routing
Github repo: https://github.com/AhmadFaraz-crypto/NextJs-14-with-antd-5.11

Top comments (0)