How to use Ant Design in a Next.js project

Last updated on January 11, 2021 A Goodman Loading... Post a comment

Next.js is a React framework that is used to build fast, high-performance, hybrid static and server side rendering web applications.

Ant Design is a UI library that provides a lot of pre-made React components like Button, DatePicker, DropDown, Drawer, etc, which can help you create beautiful and enterprise-class products.

In this article, you will learn how to use Ant Design in a Next.js project.

Basic Setup

1. Open your terminal window and navigate to the place you want your Next.js project to locate in then running:

npx create-next-app next_antd

The name is totally up to you.

2. Navigate to the project root folder:

cd next_antd

3. Install Ant Design core and its icon set with the following command:

npm install antd @ant-design/icons --save

4. Manually import the antd.css file at the very top of your pages/_app.js file:

import 'antd/dist/antd.css';

Now, we’re ready to use Ant Design components in our Next.js app.

Example

Replace the default code in your pages/index.js by this:

import { Button, Space, DatePicker, Card } from 'antd';
import { CiCircleFilled } from '@ant-design/icons';

export default function Home() {
  const onChange = () => {};
  return (
    <div style={{ padding: 100 }}>
      <Space direction="vertical">
        <Button type="primary">Primary Button</Button>
        <Button type="ghost">Ghost Button</Button>
        <DatePicker onChange={onChange} />
        <CiCircleFilled />
      </Space>
    </div>
  );
}

Go to http://localhost:3000 on your web browser and check the result:

An Error You May Run Into

If you use Ant Design version 4.10.1 or older, you may face this error:

Error: Must use import to load ES Module
required() of ES modules is not supported

Below’s the screenshot. Don’t be panic. The solution is quite simple.

To fix that error, what you need to do is just upgrade Ant Design to version 4.10.2 or later. Here’s my package.json when everything works fine:

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "@ant-design/icons": "^4.3.0",
    "antd": "^4.10.2",
    "next": "10.0.5",
    "react": "17.0.1",
    "react-dom": "17.0.1"
  }
}

Conclusion

Congratulations. You have successfully integrated Ant Design with Next.js. From here, keep on building your amazing project.

If you would like to learn more about Next.js, take a look at the following articles: How to use Font Awesome 5 with Next.jsHow to add Favicon to a Next.js app or check out our Next.js topic page for the latest tutorials and examples.

Related Articles

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x