# Ant Design Component Documentation
This file contains aggregated content from all component docs.
> Total 74 components
## _util
Source: https://ant.design/components/_util.md
---
category: Components
title: Util
description: Utilities are used to assist development and provide some common utility methods.
showImport: false
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*rRDlT7ST8DUAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*rRDlT7ST8DUAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group:
title: Other
order: 99
---
Available since `5.13.0`.
## GetRef
Get the `ref` property definition of the component, which is very useful for components that are not directly exposed or child components.
```tsx
import { Select } from 'antd';
import type { GetRef } from 'antd';
type SelectRefType = GetRef; // BaseSelectRef
```
## GetProps
Get the `props` property definition of the component:
```tsx
import { Checkbox } from 'antd';
import type { GetProps } from 'antd';
type CheckboxGroupType = GetProps;
```
Also supports getting the property definition of Context:
```tsx
import type { GetProps } from 'antd';
interface InternalContextProps {
name: string;
}
const Context = React.createContext({ name: 'Ant Design' });
type ContextType = GetProps; // InternalContextProps
```
## GetProp
Get the single `props` or `context` property definition of the component. It has encapsulated `NonNullable`, so you don't have to worry about it being empty:
```tsx
import { Select } from 'antd';
import type { GetProp, SelectProps } from 'antd';
// Both of these can work
type SelectOptionType1 = GetProp[number];
type SelectOptionType2 = GetProp[number];
type ContextOptionType = GetProp;
```
Also supports getting the return type of a function property through the third parameter `'Return'`:
```tsx
import type { GetProp } from 'antd';
interface Props {
func?: (value: number) => string;
configOrFunc?: { configA?: string } | (() => { anotherB?: string });
}
type OnChangeReturn = GetProp; // string
type ClassNamesReturn = GetProp; // { anotherB?: string }
```
---
## affix
Source: https://ant.design/components/affix.md
---
category: Components
title: Affix
description: Stick an element to the viewport.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*YSm4RI3iOJ8AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*03dxS64LxeQAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group:
title: Other
order: 7
---
## When To Use
On longer web pages, it's helpful to stick component into the viewport. This is common for menus and actions.
Please note that Affix should not cover other content on the page, especially when the size of the viewport is small.
> Notes for developers
>
> After version `5.10.0`, we rewrite Affix use FC, Some methods of obtaining `ref` and calling internal instance methods will be invalid.
## Examples
### Basic
The simplest usage.
```tsx
import React from 'react';
import { Affix, Button } from 'antd';
const App: React.FC = () => {
const [top, setTop] = React.useState(100);
const [bottom, setBottom] = React.useState(100);
return (
<>
setTop(top + 10)}>
Affix top
setBottom(bottom + 10)}>
Affix bottom
>
);
};
export default App;
```
### Callback
Callback with affixed state.
```tsx
import React from 'react';
import { Affix, Button } from 'antd';
const App: React.FC = () => (
console.log(affixed)}>
120px to affix top
);
export default App;
```
### Container to scroll.
Set a `target` for 'Affix', which is listen to scroll event of target element (default is `window`).
```tsx
import React from 'react';
import { Affix, Button } from 'antd';
const containerStyle: React.CSSProperties = {
width: '100%',
height: 100,
overflow: 'auto',
boxShadow: '0 0 0 1px #1677ff',
scrollbarWidth: 'thin',
scrollbarGutter: 'stable',
};
const style: React.CSSProperties = {
width: '100%',
height: 1000,
};
const App: React.FC = () => {
const [container, setContainer] = React.useState(null);
return (
container}>
Fixed at the top of container
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| offsetBottom | Offset from the bottom of the viewport (in pixels) | number | - | | × |
| offsetTop | Offset from the top of the viewport (in pixels) | number | 0 | | × |
| target | Specifies the scrollable area DOM node | () => Window \| HTMLElement \| null | () => window | | × |
| onChange | Callback for when Affix state is changed | (affixed?: boolean) => void | - | | × |
**Note:** Children of `Affix` must not have the property `position: absolute`, but you can set `position: absolute` on `Affix` itself:
```jsx
...
```
## FAQ
### When binding container with `target` in Affix, elements sometimes move out of the container. {#faq-target-container}
We only listen to container scroll events for performance consideration. You can add custom listeners if you still want to:
Related issues:[#3938](https://github.com/ant-design/ant-design/issues/3938) [#5642](https://github.com/ant-design/ant-design/issues/5642) [#16120](https://github.com/ant-design/ant-design/issues/16120)
### When Affix is used in a horizontal scroll container, the position of the element `left` is incorrect. {#faq-horizontal-scroll}
Affix is generally only applicable to areas with one-way scrolling, and only supports usage in vertical scrolling containers. If you want to use it in a horizontal container, you can consider implementing with the native `position: sticky` property.
Related issues:[#29108](https://github.com/ant-design/ant-design/issues/29108)
---
## alert
Source: https://ant.design/components/alert.md
---
category: Components
title: Alert
description: Display warning messages that require attention.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*QsvtS41m45UAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*gOTISoMFZV0AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group:
title: Feedback
order: 6
---
## When To Use
- When you need to show alert messages to users.
- When you need a persistent static container which is closable by user actions.
## Examples
### Basic
The simplest usage for short messages.
```tsx
import React from 'react';
import { Alert } from 'antd';
const App: React.FC = () => ;
export default App;
```
### More types
There are 4 types of Alert: `success`, `info`, `warning`, `error`.
```tsx
import React from 'react';
import { Alert } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### Filled
Hide the border with `variant="filled"`.
```tsx
import React from 'react';
import { Alert } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Closable
To show close button.
```tsx
import React from 'react';
import { Alert } from 'antd';
const onClose: React.MouseEventHandler = (e) => {
console.log(e, 'I was closed.');
};
const App: React.FC = () => (
<>
>
);
export default App;
```
### Description
Additional description for alert message.
```tsx
import React from 'react';
import { Alert } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### Icon
A relevant icon will make information clearer and more friendly.
```tsx
import React from 'react';
import { Alert } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### Banner
Display Alert as a banner at top of page.
```tsx
import React from 'react';
import { Alert } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### Loop Banner
Show a loop banner by using with [react-text-loop-next](https://npmjs.com/package/react-text-loop-next) or [react-fast-marquee](https://npmjs.com/package/react-fast-marquee).
```tsx
import React from 'react';
import { Alert } from 'antd';
import Marquee from 'react-fast-marquee';
const App: React.FC = () => (
I can be a React component, multiple React components, or just some text.
}
/>
);
export default App;
```
### Smoothly Unmount
Smoothly unmount Alert upon close.
```tsx
import React, { useState } from 'react';
import { Alert, Switch } from 'antd';
const App: React.FC = () => {
const [visible, setVisible] = useState(true);
const handleClose = () => {
setVisible(false);
};
return (
<>
{visible && (
)}
click the close button to see the effect
>
);
};
export default App;
```
### ErrorBoundary
ErrorBoundary Component for making error handling easier in [React](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary).
```tsx
import React, { useState } from 'react';
import { Alert, Button } from 'antd';
const { ErrorBoundary } = Alert;
const ThrowError: React.FC = () => {
const [error, setError] = useState();
const onClick = () => {
setError(new Error('An Uncaught Error'));
};
if (error) {
throw error;
}
return (
Click me to throw a error
);
};
const App: React.FC = () => (
);
export default App;
```
### Custom action
Custom action.
```tsx
import React from 'react';
import { Alert, Button, Flex } from 'antd';
const App: React.FC = () => (
<>
UNDO
}
closable
/>
Detail
}
/>
Done
}
closable
/>
Accept
Decline
}
closable
/>
>
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Alert by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Alert, Button, Flex } from 'antd';
import type { AlertProps, GetProp } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
border: 2px dashed #ccc;
border-radius: 8px;
padding: 12px;
`,
}));
const styleFn: AlertProps['styles'] = ({
props: { type },
}): GetProp => {
if (type === 'success') {
return {
root: {
backgroundColor: 'rgba(82, 196, 26, 0.1)',
borderColor: '#b7eb8f',
},
icon: {
color: '#52c41a',
},
};
}
if (type === 'warning') {
return {
root: {
backgroundColor: 'rgba(250, 173, 20, 0.1)',
borderColor: '#ffe58f',
},
icon: {
color: '#faad14',
},
};
}
return {};
};
const App: React.FC = () => {
const alertSharedProps: AlertProps = {
showIcon: true,
classNames: {
root: classNames.root,
},
};
return (
Action}
/>
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| action | The action of Alert | ReactNode | - | | × |
| ~~afterClose~~ | Called when close animation is finished, please use `closable.afterClose` instead | () => void | - | | × |
| banner | Whether to show as banner | boolean | false | | × |
| variant | Variant of Alert style | `outlined` \| `filled` | `outlined` | 6.4.0 | 6.4.0 |
| classNames | Customize class for each semantic structure inside the component. Supports object or function | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| closable | The config of closable | boolean \| [ClosableType](#closabletype) & React.AriaAttributes | `false` | | 5.15.0 |
| closeIcon | (Only supports global configuration) Custom close icon | ReactNode | - | × | 5.14.0 |
| description | Additional content of Alert | ReactNode | - | | × |
| errorIcon | (Only supports global configuration) Custom error icon in Alert icon | ReactNode | - | × | 6.2.0 |
| icon | Custom icon, effective when `showIcon` is true | ReactNode | - | | × |
| infoIcon | (Only supports global configuration) Custom info icon in Alert icon | ReactNode | - | × | 6.2.0 |
| ~~message~~ | Content of Alert, please use `title` instead | ReactNode | - | | × |
| ~~onClose~~ | Callback when Alert is closed, please use `closable.onClose` instead | (e: MouseEvent) => void | - | | × |
| ~~closeIcon~~ | Custom close icon, please use `closable.closeIcon` instead | ReactNode | - | - | × |
| ~~closeText~~ | Close text to show, please use `closable.closeIcon` instead | ReactNode | - | - | × |
| showIcon | Whether to show icon | boolean | false, in `banner` mode default is true | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| successIcon | (Only supports global configuration) Custom success icon in Alert icon | ReactNode | - | × | 6.2.0 |
| title | Content of Alert | ReactNode | - | | × |
| type | Type of Alert styles, options: `success`, `info`, `warning`, `error` | string | `info`, in `banner` mode default is `warning` | | × |
| warningIcon | (Only supports global configuration) Custom warning icon in Alert icon | ReactNode | - | × | 6.2.0 |
### ClosableType
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| afterClose | Called when close animation is finished | function | - | - |
| closeIcon | Custom close icon | ReactNode | - | - |
| onClose | Callback when Alert is closed | (e: MouseEvent) => void | - | - |
### Alert.ErrorBoundary
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| description | Custom error description to show | ReactNode | {{ error stack }} | |
| ~~message~~ | Custom error message to show, please use `title` instead | ReactNode | {{ error }} | |
| title | Custom error title to show | ReactNode | {{ error }} | |
## Semantic DOM
https://ant.design/components/alert/semantic.md
## Design Token
## Component Token (Alert)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| defaultPadding | Default padding | Padding \| undefined | 8px 12px |
| withDescriptionIconSize | Icon size with description | string \| number | 24 |
| withDescriptionPadding | Padding with description | Padding \| undefined | 20px 24px |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| colorError | Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. | string | |
| colorErrorBg | The background color of the error state. | string | |
| colorErrorBorder | The border color of the error state. | string | |
| colorIcon | Weak action. Such as `allowClear` or Alert close button | string | |
| colorIconHover | Weak action hover color. Such as `allowClear` or Alert close button | string | |
| colorInfo | Used to represent the operation information of the Token sequence, such as Alert, Tag, Progress, and other components use these map tokens. | string | |
| colorInfoBg | Light background color of information color. | string | |
| colorInfoBorder | Border color of information color. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorSuccess | Used to represent the token sequence of operation success, such as Result, Progress and other components will use these map tokens. | string | |
| colorSuccessBg | Light background color of success color, used for Tag and Alert success state background color | string | |
| colorSuccessBorder | Border color of success color, used for Tag and Alert success state border color | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextHeading | Control the font color of heading. | string | |
| colorWarning | Used to represent the warning map token, such as Notification, Alert, etc. Alert or Control component(like Input) will use these map tokens. | string | |
| colorWarningBg | The background color of the warning state. | string | |
| colorWarningBorder | The border color of the warning state. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeIcon | Control the font size of operation icon in Select, Cascader, etc. Normally same as fontSizeSM. | number | |
| fontSizeLG | Large font size | number | |
| lineHeight | Line height of text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| marginSM | Control the margin of an element, with a medium-small size. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseInOutCirc | Preset motion curve. | string | |
---
## anchor
Source: https://ant.design/components/anchor.md
---
category: Components
title: Anchor
description: Hyperlinks to scroll on one page.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*ufP1TLS5VvIAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*_9_eTrgvHNQAAAAAAAAAAAAADrJ8AQ/original
demo:
group:
title: Navigation
order: 3
---
## When To Use
For displaying anchor hyperlinks on page and jumping between them.
> Notes for developers
>
> After version `4.24.0`, we rewrite Anchor use FC, Some methods of obtaining `ref` and calling internal instance methods will invalid.
## Examples
### Basic
The simplest usage.
```tsx
import React from 'react';
import { Anchor, Col, Row } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Horizontal Anchor
Horizontally aligned anchors
```tsx
import React from 'react';
import { Anchor } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### Static Anchor
Do not change state when page is scrolling.
```tsx
import React from 'react';
import { Anchor } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Customize the onClick event
Clicking on an anchor does not record history.
```tsx
import React from 'react';
import { Anchor } from 'antd';
const handleClick = (
e: React.MouseEvent,
link: {
title: React.ReactNode;
href: string;
},
) => {
e.preventDefault();
console.log(link);
};
const App: React.FC = () => (
);
export default App;
```
### Customize the anchor highlight
Customize the anchor highlight.
```tsx
import React from 'react';
import { Anchor } from 'antd';
const getCurrentAnchor = () => '#anchor-demo-static';
const App: React.FC = () => (
);
export default App;
```
### Set Anchor scroll offset
Anchor target scroll to screen center.
```tsx
import React, { useEffect, useState } from 'react';
import { Anchor, Col, Row } from 'antd';
const style: React.CSSProperties = {
height: '30vh',
backgroundColor: 'rgba(0, 0, 0, 0.85)',
position: 'fixed',
top: 0,
insetInlineStart: 0,
width: '75%',
color: '#fff',
};
const App: React.FC = () => {
const topRef = React.useRef(null);
const [targetOffset, setTargetOffset] = useState();
useEffect(() => {
setTargetOffset(topRef.current?.clientHeight);
}, []);
return (
);
};
export default App;
```
### Listening for anchor link change
Listening for anchor link change.
```tsx
import React from 'react';
import { Anchor } from 'antd';
const onChange = (link: string) => {
console.log('Anchor:OnChange', link);
};
const App: React.FC = () => (
);
export default App;
```
### Replace href in history
Replace path in browser history, so back button returns to previous page instead of previous anchor item.
```tsx
import React from 'react';
import { Anchor, Col, Row } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Anchor by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Anchor, Col, Row } from 'antd';
import type { AnchorProps, GetProp } from 'antd';
const classNamesObject: AnchorProps['classNames'] = {
root: 'demo-anchor-root',
item: 'demo-anchor-item',
itemTitle: 'demo-anchor-title',
indicator: 'demo-anchor-indicator',
};
const stylesFn: AnchorProps['styles'] = (info): GetProp => {
if (info.props.direction === 'vertical') {
return {
root: {
backgroundColor: 'rgba(255,251,230,0.5)',
height: '100vh',
},
};
}
return {};
};
const items: NonNullable = [
{
key: 'part-1',
href: '#part-1',
title: 'Part 1',
},
{
key: 'part-2',
href: '#part-2',
title: 'Part 2',
},
{
key: 'part-3',
href: '#part-3',
title: 'Part 3',
},
];
const App: React.FC = () => {
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Anchor Props
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| affix | Fixed mode of Anchor | boolean \| Omit | true | object: 5.19.0 | × |
| bounds | Bounding distance of anchor area | number | 5 | | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| getContainer | Scrolling container | () => HTMLElement | () => window | | × |
| getCurrentAnchor | Customize the anchor highlight | (activeLink: string) => string | - | | × |
| offsetTop | Pixels to offset from top when calculating position of scroll | number | 0 | | × |
| showInkInFixed | Whether show ink-square when `affix={false}` | boolean | false | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| targetOffset | Anchor scroll offset, default as `offsetTop`, [example](#anchor-demo-targetoffset) | number | - | | × |
| onChange | Listening for anchor link change | (currentActiveLink: string) => void | | | × |
| onClick | Set the handler to handle `click` event | (e: MouseEvent, link: object) => void | - | | × |
| items | Data configuration option content, support nesting through children | { key, href, title, target, children }\[] [see](#anchoritem) | - | 5.1.0 | × |
| direction | Set Anchor direction | `vertical` \| `horizontal` | `vertical` | 5.2.0 | × |
| replace | Replace items' href in browser history instead of pushing it | boolean | false | 5.7.0 | × |
### AnchorItem
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| key | The unique identifier of the Anchor Link | string \| number | - | |
| href | The target of hyperlink | string | | |
| target | Specifies where to display the linked URL | string | | |
| title | The content of hyperlink | ReactNode | | |
| children | Nested Anchor Link, `Attention: This attribute does not support horizontal orientation` | [AnchorItem](#anchoritem)\[] | - | |
| replace | Replace item href in browser history instead of pushing it | boolean | false | 5.7.0 |
| targetOffset | Customize scroll offset for this anchor link. It takes precedence over the `targetOffset` prop of the Anchor component | number | - | 6.4.0 |
### Link Props
We recommend using the items form instead.
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| href | The target of hyperlink | string | | |
| target | Specifies where to display the linked URL | string | | |
| title | The content of hyperlink | ReactNode | | |
| targetOffset | Customize scroll offset for this anchor link. It takes precedence over the `targetOffset` prop of the Anchor component | number | - | 6.4.0 |
## Semantic DOM
https://ant.design/components/anchor/semantic.md
## Design Token
## Component Token (Anchor)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| linkPaddingBlock | Vertical padding of link | number | 4 |
| linkPaddingInlineStart | Horizontal padding of link | number | 16 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorSplit | Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeLG | Large font size | number | |
| lineHeight | Line height of text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| lineWidthBold | The default line width of the outline class components, such as Button, Input, Select, etc. | number | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| paddingXXS | Control the extra extra small padding of the element. | number | |
## FAQ
### In version `5.25.0+`, the `:target` pseudo-class of the destination element does not take effect as expected after anchor navigation. {#faq-target-pseudo-class}
For the purpose of page performance optimization, the implementation of anchor navigation has been changed from `window.location.href` to `window.history.pushState/replaceState`. Since `pushState/replaceState` does not trigger a page reload, the browser will not automatically update the matching state of the `:target` pseudo-class. To resolve this issue, you can manually construct the full URL: `href = window.location.origin + window.location.pathname + '#xxx'`.
Related issues: [#53143](https://github.com/ant-design/ant-design/issues/53143) [#54255](https://github.com/ant-design/ant-design/issues/54255)
---
## app
Source: https://ant.design/components/app.md
---
category: Components
group: Other
title: App
description: Application wrapper for some global usages.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*HJz8SZos2wgAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*oC92TK44Ex8AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
- Provide reset styles based on `.ant-app` element.
- You could use static methods of `message/notification/Modal` from `useApp` without writing `contextHolder` manually.
## Examples
### Basic
Get instance for `message`, `notification`, `modal`.
```tsx
import React from 'react';
import { App, Button, Space } from 'antd';
// Sub page
const Page: React.FC = () => {
const { message, modal, notification } = App.useApp();
const showMessage = () => {
message.success('Success!');
};
const showModal = () => {
modal.warning({
title: 'This is a warning message',
content: 'some messages...some messages...',
});
};
const showNotification = () => {
notification.info({
title: 'Notification topLeft',
description: 'Hello, Ant Design!!',
placement: 'topLeft',
});
};
return (
Open message
Open modal
Open notification
);
};
// Entry component
export default () => (
);
```
### Hooks config
Config for `message`, `notification`.
```tsx
import React from 'react';
import { App, Button, Space } from 'antd';
// Sub page
const Page: React.FC = () => {
const { message, notification } = App.useApp();
const showMessage = () => {
message.success('Success!');
};
const showNotification = () => {
notification.info({
title: 'Notification',
description: 'Hello, Ant Design!!',
});
};
return (
Message for only one
Notification for bottomLeft
);
};
// Entry component
export default () => (
);
```
## How to use
### Basic usage
App provides upstream and downstream method calls through `Context`, because useApp needs to be used as a subcomponent, we recommend encapsulating App at the top level in the application.
```tsx
import React from 'react';
import { App } from 'antd';
const MyPage: React.FC = () => {
const { message, notification, modal } = App.useApp();
message.success('Good!');
notification.info({ title: 'Good' });
modal.warning({ title: 'Good' });
// ....
// other message, notification, modal static function
return Hello world
;
};
const MyApp: React.FC = () => (
);
export default MyApp;
```
Note: App.useApp must be available under App.
### Sequence with ConfigProvider
The App component can only use the token in the `ConfigProvider`, if you need to use the Token, the ConfigProvider and the App component must appear in pairs.
```tsx
...
```
### Embedded usage scenarios (if not necessary, try not to do nesting) {#embedded-usage-scenarios}
```tsx
...
...
```
### Global scene (redux scene) {#global-scene-redux}
```tsx
// Entry component
import { App } from 'antd';
import type { MessageInstance } from 'antd/es/message/interface';
import type { ModalStaticFunctions } from 'antd/es/modal/confirm';
import type { NotificationInstance } from 'antd/es/notification/interface';
let message: MessageInstance;
let notification: NotificationInstance;
let modal: Omit;
export default () => {
const staticFunction = App.useApp();
message = staticFunction.message;
modal = staticFunction.modal;
notification = staticFunction.notification;
return null;
};
export { message, modal, notification };
```
```tsx
// sub page
import React from 'react';
import { Button, Space } from 'antd';
import { message } from './store';
export default () => {
const showMessage = () => {
message.success('Success!');
};
return (
Open message
);
};
```
## API
Common props ref:[Common props](/docs/react/common-props)
> This component is available since `antd@5.1.0`.
### App
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| component | Config render element, if `false` will not create DOM node | ComponentType \| false | div | 5.11.0 | × |
| message | Global config for Message | [MessageConfig](/components/message/#messageconfig) | - | 5.3.0 | × |
| notification | Global config for Notification | [NotificationConfig](/components/notification/#notificationconfig) | - | 5.3.0 | × |
## Design Token
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| lineHeight | Line height of text. | number | |
## FAQ
### CSS Var doesn't work inside `` {#faq-css-var-component-false}
Make sure the App `component` is a valid html tag, so when you're turning on CSS variables, there's a container to hold the CSS class name. If not set, it defaults to the `div` tag. If set to `false`, no additional DOM nodes will be created, and no default styles will be provided.
---
## auto-complete
Source: https://ant.design/components/auto-complete.md
---
category: Components
title: AutoComplete
description: Autocomplete function of input field.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*g8THS4NpV6sAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*WERTQ6qvgEYAAAAAAAAAAAAADrJ8AQ/original
group:
title: Data Entry
order: 4
demo:
cols: 2
---
## When To Use
- When you need an input box instead of a selector.
- When you need input suggestions or helping text.
The differences with Select are:
- AutoComplete is an input box with text hints, and users can type freely. The keyword is aiding **input**.
- Select is selecting among given choices. The keyword is **select**.
## Examples
### Basic Usage
Basic Usage, set data source of autocomplete with `options` property.
```tsx
import React, { useState } from 'react';
import { AutoComplete } from 'antd';
import type { AutoCompleteProps } from 'antd';
const mockVal = (str: string, repeat = 1) => ({
value: str.repeat(repeat),
});
const App: React.FC = () => {
const [value, setValue] = useState('');
const [options, setOptions] = useState([]);
const [anotherOptions, setAnotherOptions] = useState([]);
const getPanelValue = (searchText: string) =>
!searchText ? [] : [mockVal(searchText), mockVal(searchText, 2), mockVal(searchText, 3)];
const onSelect = (data: string) => {
console.log('onSelect', data);
};
const onChange = (data: string) => {
setValue(data);
};
return (
<>
setOptions(getPanelValue(text)),
}}
placeholder="input here"
/>
setAnotherOptions(getPanelValue(text)) }}
options={anotherOptions}
style={{ width: 200 }}
onSelect={onSelect}
onChange={onChange}
placeholder="control mode"
/>
>
);
};
export default App;
```
### Customized
You could set custom `Option` label
```tsx
import React from 'react';
import { AutoComplete } from 'antd';
import type { AutoCompleteProps } from 'antd';
const App: React.FC = () => {
const [options, setOptions] = React.useState([]);
const handleSearch = (value: string) => {
setOptions(() => {
if (!value || value.includes('@')) {
return [];
}
return ['gmail.com', '163.com', 'qq.com'].map((domain) => ({
label: `${value}@${domain}`,
value: `${value}@${domain}`,
}));
});
};
return (
);
};
export default App;
```
### Customize Input Component
Customize Input Component
```tsx
import React, { useState } from 'react';
import { AutoComplete, Input } from 'antd';
import type { AutoCompleteProps } from 'antd';
const { TextArea } = Input;
const App: React.FC = () => {
const [options, setOptions] = useState([]);
const handleSearch = (value: string) => {
setOptions(
!value ? [] : [{ value }, { value: value + value }, { value: value + value + value }],
);
};
const handleKeyPress = (ev: React.KeyboardEvent) => {
console.log('handleKeyPress', ev);
};
const onSelect = (value: string) => {
console.log('onSelect', value);
};
return (
);
};
export default App;
```
### Non-case-sensitive AutoComplete
A non-case-sensitive AutoComplete
```tsx
import React from 'react';
import { AutoComplete } from 'antd';
const options = [
{ value: 'Burns Bay Road' },
{ value: 'Downing Street' },
{ value: 'Wall Street' },
];
const App: React.FC = () => (
option!.value.toUpperCase().includes(inputValue.toUpperCase()),
}}
/>
);
export default App;
```
### Lookup-Patterns - Certain Category
Demonstration of [Lookup Patterns: Certain Category](https://ant.design/docs/spec/reaction#lookup-patterns). Basic Usage, set options of autocomplete with `options` property.
```css
.certain-category-search-dropdown .ant-select-dropdown-menu-item-group-title {
color: #666;
font-weight: bold;
}
.certain-category-search-dropdown .ant-select-dropdown-menu-item-group {
border-bottom: 1px solid #f6f6f6;
}
.certain-category-search-dropdown .ant-select-dropdown-menu-item {
padding-inline-start: 16px;
}
.certain-category-search-dropdown .ant-select-dropdown-menu-item.show-all {
text-align: center;
cursor: default;
}
.certain-category-search-dropdown .ant-select-dropdown-menu {
max-height: 300px;
}
```
```tsx
import React from 'react';
import { UserOutlined } from '@ant-design/icons';
import { AutoComplete, Flex, Input } from 'antd';
const Title: React.FC> = (props) => (
{props.title}
more
);
const renderItem = (title: string, count: number) => ({
value: title,
label: (
{title}
{count}
),
});
const options = [
{
label: ,
options: [renderItem('AntDesign', 10000), renderItem('AntDesign UI', 10600)],
},
{
label: ,
options: [renderItem('AntDesign UI FAQ', 60100), renderItem('AntDesign FAQ', 30010)],
},
{
label: ,
options: [renderItem('AntDesign design language', 100000)],
},
];
const App: React.FC = () => (
);
export default App;
```
### Lookup-Patterns - Uncertain Category
Demonstration of [Lookup Patterns: Uncertain Category](https://ant.design/docs/spec/reaction#lookup-patterns).
```tsx
import React, { useState } from 'react';
import { AutoComplete, Input } from 'antd';
import type { AutoCompleteProps } from 'antd';
const getRandomInt = (max: number, min = 0) => Math.floor(Math.random() * (max - min + 1)) + min;
const searchResult = (query: string) =>
Array.from({ length: getRandomInt(5) })
.join('.')
.split('.')
.map((_, idx) => {
const category = `${query}${idx}`;
return {
value: category,
label: (
Found {query} on{' '}
{category}
{getRandomInt(200, 100)} results
),
};
});
const App: React.FC = () => {
const [options, setOptions] = useState([]);
const handleSearch = (value: string) => {
setOptions(value ? searchResult(value) : []);
};
const onSelect = (value: string) => {
console.log('onSelect', value);
};
return (
);
};
export default App;
```
### Status
Add status to AutoComplete with `status`, which could be `error` or `warning`.
```tsx
import React, { useState } from 'react';
import { AutoComplete, Space } from 'antd';
import type { AutoCompleteProps } from 'antd';
const mockVal = (str: string, repeat = 1) => ({
value: str.repeat(repeat),
});
const App: React.FC = () => {
const [options, setOptions] = useState([]);
const [anotherOptions, setAnotherOptions] = useState([]);
const getPanelValue = (searchText: string) =>
!searchText ? [] : [mockVal(searchText), mockVal(searchText, 2), mockVal(searchText, 3)];
return (
setOptions(getPanelValue(text)),
}}
status="error"
style={{ width: 200 }}
/>
setAnotherOptions(getPanelValue(text)),
}}
status="warning"
style={{ width: 200 }}
/>
);
};
export default App;
```
### Variants
There are `outlined`, `filled`, `borderless`, and `underlined` variants to choose from.
```tsx
import React, { useState } from 'react';
import { AutoComplete, Flex } from 'antd';
import type { AutoCompleteProps } from 'antd';
const mockVal = (str: string, repeat = 1) => ({
value: str.repeat(repeat),
});
const App: React.FC = () => {
const [options, setOptions] = useState([]);
const getPanelValue = (searchText: string) =>
!searchText ? [] : [mockVal(searchText), mockVal(searchText, 2), mockVal(searchText, 3)];
return (
setOptions(getPanelValue(text)) }}
onSelect={globalThis.console.log}
/>
setOptions(getPanelValue(text)) }}
onSelect={globalThis.console.log}
variant="filled"
/>
setOptions(getPanelValue(text)) }}
onSelect={globalThis.console.log}
variant="borderless"
/>
setOptions(getPanelValue(text))}
onSelect={globalThis.console.log}
variant="underlined"
/>
);
};
export default App;
```
### Customize clear button
Customize clear button
```tsx
import React, { useState } from 'react';
import { CloseSquareFilled } from '@ant-design/icons';
import { AutoComplete } from 'antd';
import type { AutoCompleteProps } from 'antd';
const mockVal = (str: string, repeat = 1) => ({
value: str.repeat(repeat),
});
const App: React.FC = () => {
const [options, setOptions] = useState([]);
const getPanelValue = (searchText: string) =>
!searchText ? [] : [mockVal(searchText), mockVal(searchText, 2), mockVal(searchText, 3)];
return (
<>
setOptions(getPanelValue(text)) }}
placeholder="UnClearable"
allowClear={false}
/>
setOptions(getPanelValue(text)) }}
placeholder="Customized clear icon"
allowClear={{ clearIcon: }}
/>
>
);
};
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of AutoComplete by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { AutoComplete, Flex } from 'antd';
import type { AutoCompleteProps, GetProp } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
border-radius: 4px;
`,
}));
const stylesObject: AutoCompleteProps['styles'] = {
popup: {
root: { borderWidth: 1, borderColor: '#1890ff' },
list: { backgroundColor: 'rgba(240,240,240, 0.85)' },
listItem: { color: '#272727' },
},
};
const stylesFn: AutoCompleteProps['styles'] = ({
props,
}): GetProp => {
if (props.variant === 'filled') {
return {
popup: {
root: { borderWidth: 1, borderColor: '#ccc' },
list: { backgroundColor: 'rgba(240,240,240, 0.85)' },
listItem: { color: '#272727' },
},
};
}
return {};
};
const options: AutoCompleteProps['options'] = [
{ value: 'Burnaby' },
{ value: 'Seattle' },
{ value: 'Los Angeles' },
{ value: 'San Francisco' },
{ value: 'Meet student' },
];
const App: React.FC = () => {
const sharedProps: AutoCompleteProps = {
options,
classNames: {
root: classNames.root,
},
style: { width: 200 },
};
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| allowClear | Show clear button | boolean \| { clearIcon?: ReactNode } | false | 5.8.0: Support Object type |
| backfill | If backfill selected item the input when using keyboard | boolean | false | |
| children | Customize input element | HTMLInputElement \| HTMLTextAreaElement \| React.ReactElement<InputProps> | <Input /> | |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| ~~dataSource~~ | Data source of autocomplete options, please use `options` instead | DataSourceItemType[] | - | - |
| defaultActiveFirstOption | Whether active first option by default | boolean | true | |
| defaultOpen | Initial open state of dropdown | boolean | - | |
| defaultValue | Initial selected option | string | - | |
| disabled | Whether disabled select | boolean | false | |
| ~~dropdownClassName~~ | The className of dropdown menu, please use `classNames.popup.root` instead | string | - | - |
| ~~dropdownMatchSelectWidth~~ | Determine whether the dropdown menu and the input are the same width, please use `popupMatchSelectWidth` instead | boolean \| number | true | - |
| ~~dropdownRender~~ | Customize dropdown content, use `popupRender` instead | (originNode: ReactNode) => ReactNode | - | 4.24.0 |
| popupRender | Customize dropdown content | (originNode: ReactNode) => ReactNode | - | |
| ~~dropdownStyle~~ | The style of dropdown menu, use `styles.popup.root` instead | CSSProperties | - | |
| ~~popupClassName~~ | The className of dropdown menu, use `classNames.popup.root` instead | string | - | 4.23.0 |
| popupMatchSelectWidth | Determine whether the dropdown menu and the select input are the same width. Default set `min-width` same as input. Will ignore when value less than select width. `false` will disable virtual scroll | boolean \| number | true | |
| ~~filterOption~~ | If true, filter options by input, if function, filter options against it. The function will receive two arguments, `inputValue` and `option`, if the function returns true, the option will be included in the filtered set; Otherwise, it will be excluded | boolean \| function(inputValue, option) | true | |
| getPopupContainer | Parent node of the dropdown. Default to body, if you encountered positioning problems during scroll, try changing to the scrollable area and position relative to it. [Example](https://codesandbox.io/s/4j168r7jw0) | function(triggerNode) | () => document.body | |
| notFoundContent | Specify content to show when no result matches | ReactNode | - | |
| open | Controlled open state of dropdown | boolean | - | |
| options | Select options. Will get better perf than jsx definition | { label, value }\[] | - | |
| placeholder | The placeholder of input | string | - | |
| showSearch | search for configuration | true \| [Object](#showsearch) | true | |
| status | Set validation status | 'error' \| 'warning' | - | 4.19.0 |
| size | The size of the input box | `large` \| `medium` \| `small` | - | |
| value | Selected option | string | - | |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| variant | Variants of input | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 |
| virtual | Disable virtual scroll when set to false | boolean | true | 4.1.0 |
| onBlur | Called when leaving the component | function() | - | |
| onChange | Called when selecting an option or changing an input value | function(value) | - | |
| ~~onDropdownVisibleChange~~ | Called when dropdown open, use `onOpenChange` instead | (open: boolean) => void | - | |
| onOpenChange | Called when dropdown open | (open: boolean) => void | - | |
| onFocus | Called when entering the component | function() | - | |
| ~~onSearch~~ | Called when searching items | function(value) | - | |
| onSelect | Called when a option is selected. param is option's value and option instance | function(value, option) | - | |
| onClear | Called when clear | function | - | 4.6.0 |
| onInputKeyDown | Called when key pressed | (event: KeyboardEvent) => void | - | |
| onPopupScroll | Called when dropdown scrolls | (event: UIEvent) => void | - | |
### showSearch
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| filterOption | If true, filter options by input, if function, filter options against it. The function will receive two arguments, `inputValue` and `option`, if the function returns true, the option will be included in the filtered set; Otherwise, it will be excluded | boolean \| function(inputValue, option) | true | |
| onSearch | Called when searching items | function(value) | - | |
## Methods
| Name | Description | Version |
| ------- | ------------ | ------- |
| blur() | Remove focus | |
| focus() | Get focus | |
## Semantic DOM
https://ant.design/components/auto-complete/semantic.md
## Design Token
## Component Token (Select)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| activeBorderColor | Active border color | string | #1677ff |
| activeOutlineColor | Active outline color | string | rgba(5,145,255,0.1) |
| clearBg | Background color of clear button | string | #ffffff |
| hoverBorderColor | Hover border color | string | #4096ff |
| multipleItemBg | Background color of multiple tag | string | rgba(0,0,0,0.06) |
| multipleItemBorderColor | Border color of multiple tag | string | transparent |
| multipleItemBorderColorDisabled | Border color of multiple tag when disabled | string | transparent |
| multipleItemColorDisabled | Text color of multiple tag when disabled | string | rgba(0,0,0,0.25) |
| multipleItemHeight | Height of multiple tag | number | 24 |
| multipleItemHeightLG | Height of multiple tag with large size | number | 32 |
| multipleItemHeightSM | Height of multiple tag with small size | number | 16 |
| multipleSelectorBgDisabled | Background color of multiple selector when disabled | string | rgba(0,0,0,0.04) |
| optionActiveBg | Background color when option is active | string | rgba(0,0,0,0.04) |
| optionFontSize | Font size of option | number | 14 |
| optionHeight | Height of option | number | 32 |
| optionLineHeight | Line height of option | LineHeight \| undefined | 1.5714285714285714 |
| optionPadding | Padding of option | Padding \| undefined | 5px 12px |
| optionSelectedBg | Background color when option is selected | string | #e6f4ff |
| optionSelectedColor | Text color when option is selected | string | rgba(0,0,0,0.88) |
| optionSelectedFontWeight | Font weight when option is selected | FontWeight \| undefined | 600 |
| selectorBg | Background color of selector | string | #ffffff |
| showArrowPaddingInlineEnd | Inline end padding of arrow | number | 18 |
| singleItemHeightLG | Height of single selected item with large size | number | 40 |
| zIndexPopup | z-index of dropdown | number | 1050 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadius | Border radius of base components | number | |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| borderRadiusXS | XS size border radius, used in some small border radius components, such as Segmented, Arrow and other components with small border radius. | number | |
| boxShadowSecondary | Control the secondary box shadow style of an element. | string | |
| colorBgBase | Used to derive the base variable of the background color gradient. In v5, we added a layer of background color derivation algorithm to produce map token of background color. But PLEASE DO NOT USE this Seed Token directly in the code! | string | |
| colorBgContainer | Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. | string | |
| colorBgContainerDisabled | Control the background color of container in disabled state. | string | |
| colorBgElevated | Container background color of the popup layer, in dark mode the color value of this token will be a little brighter than `colorBgContainer`. E.g: modal, pop-up, menu, etc. | string | |
| colorBorder | Default border color, used to separate different elements, such as: form separator, card separator, etc. | string | |
| colorBorderDisabled | Control the border color of the element in the disabled state. | string | |
| colorError | Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. | string | |
| colorErrorAffix | Control the color of form control prefix/suffix in error state. | string | |
| colorErrorBg | The background color of the error state. | string | |
| colorErrorBgHover | The hover state background color of the error state. | string | |
| colorErrorBorderHover | The hover state border color of the error state. | string | |
| colorErrorOutline | Control the outline color of input component in error state. | string | |
| colorErrorText | The default state of the text in the error color. | string | |
| colorFillSecondary | The second level of fill color can outline the shape of the element more clearly, such as Rate, Skeleton, etc. It can also be used as the Hover state of the third level of fill color, such as Table, etc. | string | |
| colorFillTertiary | The third level of fill color is used to outline the shape of the element, such as Slider, Segmented, etc. If there is no emphasis requirement, it is recommended to use the third level of fill color as the default fill color. | string | |
| colorIcon | Weak action. Such as `allowClear` or Alert close button | string | |
| colorIconHover | Weak action hover color. Such as `allowClear` or Alert close button | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorSplit | Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDescription | Control the font color of text description. | string | |
| colorTextDisabled | Control the color of text in disabled state. | string | |
| colorTextPlaceholder | Control the color of placeholder text. | string | |
| colorTextQuaternary | The fourth level of text color is the lightest text color, such as form input prompt text, disabled color text, etc. | string | |
| colorWarning | Used to represent the warning map token, such as Notification, Alert, etc. Alert or Control component(like Input) will use these map tokens. | string | |
| colorWarningAffix | Control the color of form control prefix/suffix in warning state. | string | |
| colorWarningBg | The background color of the warning state. | string | |
| colorWarningBgHover | The hover state background color of the warning state. | string | |
| colorWarningHover | The hover state of the warning color. | string | |
| colorWarningOutline | Control the outline color of input component in warning state. | string | |
| controlHeight | The height of the basic controls such as buttons and input boxes in Ant Design | number | |
| controlHeightLG | LG component height | number | |
| controlHeightSM | SM component height | number | |
| controlItemBgActiveHover | Control the background color of control component item when hovering and active. | string | |
| controlOutlineWidth | Control the outline width of input component. | number | |
| controlPaddingHorizontal | Control the horizontal padding of an element. | number | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeIcon | Control the font size of operation icon in Select, Cascader, etc. Normally same as fontSizeSM. | number | |
| fontSizeLG | Large font size | number | |
| fontSizeSM | Small font size | number | |
| lineHeight | Line height of text. | number | |
| lineHeightLG | Line height of large text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseInOut | Preset motion curve. | string | |
| motionEaseInOutCirc | Preset motion curve. | string | |
| motionEaseInQuint | Preset motion curve. | string | |
| motionEaseOutCirc | Preset motion curve. | string | |
| motionEaseOutQuint | Preset motion curve. | string | |
| paddingSM | Control the small padding of the element. | number | |
| paddingXS | Control the extra small padding of the element. | number | |
| paddingXXS | Control the extra extra small padding of the element. | number | |
## FAQ
### Why doesn't the text composition system work well with onSearch in controlled mode? {#faq-controlled-onsearch-composition}
Please use `onChange` to manage control state. `onSearch` is used for searching input which is not the same as `onChange`. Besides, clicking on the option will not trigger the `onSearch` event.
Related issue: [#18230](https://github.com/ant-design/ant-design/issues/18230) [#17916](https://github.com/ant-design/ant-design/issues/17916)
### Why won't a controlled open AutoComplete display a drop-down menu when options are empty? {#faq-empty-options-controlled-open}
The AutoComplete component is essentially an extension of the Input form element. When the `options` property is empty, displaying empty text could mislead the user into believing the component is not operational, when in fact they are still able to input text. To avoid confusion, the `open` property will not display the drop-down menu when set to `true` and in combination with an empty `options` property. The `open` property must be used in conjunction with the `options` property.
---
## avatar
Source: https://ant.design/components/avatar.md
---
category: Components
title: Avatar
description: Used to represent users or things, supporting the display of images, icons, or characters.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*JJBSS5lBG4IAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*YbgyQaRGz-UAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group:
title: Data Display
order: 5
---
## Examples
### Basic
Three sizes and two shapes are available.
```tsx
import React from 'react';
import { UserOutlined } from '@ant-design/icons';
import { Avatar, Space } from 'antd';
const App: React.FC = () => (
} />
} />
} />
} />
} />
} />
} />
} />
} />
} />
);
export default App;
```
### Type
Image, Icon and letter are supported, and the latter two kinds of avatar can have custom colors and background colors.
```tsx
import React from 'react';
import { UserOutlined } from '@ant-design/icons';
import { Avatar, Space } from 'antd';
const url = 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg';
const App: React.FC = () => (
} />
U
USER
} />
U
} />
);
export default App;
```
### Autoset Font Size
For letter type Avatar, when the letters are too long to display, the font size can be automatically adjusted according to the width of the Avatar. You can also use `gap` to set the unit distance between left and right sides.
```tsx
import React, { useState } from 'react';
import { Avatar, Button } from 'antd';
const UserList = ['U', 'Lucy', 'Tom', 'Edward'];
const ColorList = ['#f56a00', '#7265e6', '#ffbf00', '#00a2ae'];
const GapList = [4, 3, 2, 1];
const App: React.FC = () => {
const [user, setUser] = useState(UserList[0]);
const [color, setColor] = useState(ColorList[0]);
const [gap, setGap] = useState(GapList[0]);
const changeUser = () => {
const index = UserList.indexOf(user);
setUser(index < UserList.length - 1 ? UserList[index + 1] : UserList[0]);
setColor(index < ColorList.length - 1 ? ColorList[index + 1] : ColorList[0]);
};
const changeGap = () => {
const index = GapList.indexOf(gap);
setGap(index < GapList.length - 1 ? GapList[index + 1] : GapList[0]);
};
return (
<>
{user}
ChangeUser
changeGap
>
);
};
export default App;
```
### With Badge
Usually used for reminders and notifications.
```tsx
import React from 'react';
import { UserOutlined } from '@ant-design/icons';
import { Avatar, Badge, Space } from 'antd';
const App: React.FC = () => (
} />
} />
);
export default App;
```
### Avatar.Group
Avatar group display.
```tsx
import React from 'react';
import { AntDesignOutlined, UserOutlined } from '@ant-design/icons';
import { Avatar, Divider, Tooltip } from 'antd';
const App: React.FC = () => (
<>
K
} />
} />
K
} />
} />
K
} />
} />
K
} />
} />
A
K
} />
} />
>
);
export default App;
```
### Responsive Size
Avatar size can be automatically adjusted based on the screen size.
```tsx
import React from 'react';
import { AntDesignOutlined } from '@ant-design/icons';
import { Avatar } from 'antd';
const App: React.FC = () => (
}
/>
);
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Avatar
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| alt | This attribute defines the alternative text describing the image | string | - | | × |
| gap | Letter type unit distance between left and right sides | number | 4 | 4.3.0 | × |
| icon | Custom icon type for an icon avatar | ReactNode | - | | × |
| shape | The shape of avatar | `circle` \| `square` | `circle` | | × |
| size | The size of the avatar | number \| `large` \| `medium` \| `small` \| { xs: number, sm: number, ...} | `medium` | 4.7.0 | × |
| src | The address of the image for an image avatar or image element | string \| ReactNode | - | ReactNode: 4.8.0 | × |
| srcSet | A list of sources to use for different screen resolutions | string | - | | × |
| draggable | Whether the picture is allowed to be dragged | boolean \| `'true'` \| `'false'` | true | | × |
| crossOrigin | CORS settings attributes | `'anonymous'` \| `'use-credentials'` \| `''` | - | 4.17.0 | × |
| onError | Handler when img load error, return false to prevent default fallback behavior | () => boolean | - | | × |
> Tip: You can set `icon` or `children` as the fallback for image load error, with the priority of `icon` > `children`
### Avatar.Group 4.5.0+
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| max | Set maximum display related configurations | `{ count?: number; style?: CSSProperties; popover?: PopoverProps }` | - | 5.18.0 |
| ~~maxCount~~ | Deprecated, please use `max={{ count: number }}` | number | - | |
| ~~maxPopoverPlacement~~ | Deprecated, please use `max={{ popover: PopoverProps }}` | `top` \| `bottom` | `top` | |
| ~~maxPopoverTrigger~~ | Deprecated, please use `max={{ popover: PopoverProps }}` | `hover` \| `focus` \| `click` | `hover` | |
| ~~maxStyle~~ | Deprecated, please use `max={{ style: CSSProperties }}` | CSSProperties | - | |
| size | The size of the avatar | number \| `large` \| `medium` \| `small` \| { xs: number, sm: number, ...} | `medium` | 4.8.0 |
| shape | The shape of the avatar | `circle` \| `square` | `circle` | 5.8.0 |
## Design Token
## Component Token (Avatar)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| containerSize | Size of Avatar | number | 32 |
| containerSizeLG | Size of large Avatar | number | 40 |
| containerSizeSM | Size of small Avatar | number | 24 |
| groupBorderColor | Border color of avatars in a group | string | #ffffff |
| groupOverlapping | Overlapping of avatars in a group | number | -8 |
| groupSpace | Spacing between avatars in a group | number | 4 |
| iconFontSize | Font size of Avatar icon | number | 18 |
| iconFontSizeLG | Font size of large Avatar icon | string \| number | 24 |
| iconFontSizeSM | Font size of small Avatar icon | number | 14 |
| textFontSize | Font size of Avatar | number | 14 |
| textFontSizeLG | Font size of large Avatar | number | 14 |
| textFontSizeSM | Font size of small Avatar | number | 14 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadius | Border radius of base components | number | |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextLightSolid | Control the highlight color of text with background color, such as the text in Primary Button components. | string | |
| colorTextPlaceholder | Control the color of placeholder text. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| lineHeight | Line height of text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
---
## badge
Source: https://ant.design/components/badge.md
---
category: Components
title: Badge
description: Small numerical value or status descriptor for UI elements.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*e0qITYqF394AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*v8EQT7KoGbcAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group: Data Display
---
## When To Use
Badge normally appears in proximity to notifications or user avatars with eye-catching appeal, typically displaying unread messages count.
## Examples
### Basic
Simplest Usage. Badge will be hidden when `count` is `0`, but we can use `showZero` to show it.
```tsx
import React from 'react';
import { ClockCircleOutlined } from '@ant-design/icons';
import { Avatar, Badge, Space } from 'antd';
const App: React.FC = () => (
}>
);
export default App;
```
### Standalone
Used in standalone when children is empty.
```tsx
import React, { useState } from 'react';
import { ClockCircleOutlined } from '@ant-design/icons';
import { Badge, Space, Switch } from 'antd';
const App: React.FC = () => {
const [show, setShow] = useState(true);
return (
setShow(!show)} />
: 0} />
);
};
export default App;
```
### Overflow Count
`${overflowCount}+` is displayed when count is larger than `overflowCount`. The default value of `overflowCount` is `99`.
```tsx
import React from 'react';
import { Avatar, Badge, Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Red badge
This will simply display a red badge, without a specific count. If count equals 0, it won't display the dot.
```tsx
import React from 'react';
import { NotificationOutlined } from '@ant-design/icons';
import { Badge, Space } from 'antd';
const App: React.FC = () => (
Link something
);
export default App;
```
### Dynamic
The count will be animated as it changes.
```tsx
import React, { useState } from 'react';
import { MinusOutlined, PlusOutlined, QuestionOutlined } from '@ant-design/icons';
import { Avatar, Badge, Button, Space, Switch } from 'antd';
const App: React.FC = () => {
const [count, setCount] = useState(5);
const [show, setShow] = useState(true);
const increase = () => {
setCount(count + 1);
};
const decline = () => {
let newCount = count - 1;
if (newCount < 0) {
newCount = 0;
}
setCount(newCount);
};
const random = () => {
const newCount = Math.floor(Math.random() * 100);
setCount(newCount);
};
const onChange = (checked: boolean) => {
setShow(checked);
};
return (
} />
} />
} />
);
};
export default App;
```
### Clickable
The badge can be wrapped with `a` tag to make it linkable.
```tsx
import React from 'react';
import { Avatar, Badge } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Offset
Set offset of the badge dot, the format is `[left, top]`, which represents the offset of the status dot from the left and top of the default position.
```tsx
import React from 'react';
import { Avatar, Badge } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Size
Set size of numeral Badge.
```tsx
import React from 'react';
import { Avatar, Badge, Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Status
Standalone badge with status.
```tsx
import React from 'react';
import { Badge, Space } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### Colorful Badge
We preset a series of colorful Badge styles for use in different situations. You can also set it to a hex color string for custom color.
```tsx
import React from 'react';
import { Badge, Divider, Space } from 'antd';
const colors = [
'pink',
'red',
'yellow',
'orange',
'cyan',
'green',
'blue',
'purple',
'geekblue',
'magenta',
'volcano',
'gold',
'lime',
];
const App: React.FC = () => (
<>
Presets
{colors.map((color) => (
))}
Custom
>
);
export default App;
```
### Ribbon
Use ribbon badge.
```tsx
import React from 'react';
import { Badge, Card, Space } from 'antd';
const App: React.FC = () => (
and raises the spyglass.
and raises the spyglass.
and raises the spyglass.
and raises the spyglass.
and raises the spyglass.
and raises the spyglass.
and raises the spyglass.
and raises the spyglass.
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Badge by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Avatar, Badge, Card, Flex, Space } from 'antd';
import type { BadgeProps, GetProp } from 'antd';
import { createStaticStyles } from 'antd-style';
import type { RibbonProps } from 'antd/es/badge/Ribbon';
const badgeClassNames = createStaticStyles(({ css }) => ({
indicator: css`
font-size: 10px;
`,
}));
const ribbonClassNames = createStaticStyles(({ css }) => ({
root: css`
width: 400px;
border: 1px solid #d9d9d9;
border-radius: 10px;
`,
}));
const badgeStyles: BadgeProps['styles'] = {
root: {
borderRadius: 8,
},
};
const ribbonStyles: RibbonProps['styles'] = {
indicator: {
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
},
};
const badgeStylesFn: BadgeProps['styles'] = (info): GetProp => {
if (info.props.size === 'medium') {
return {
indicator: {
fontSize: 14,
backgroundColor: '#696FC7',
},
};
}
return {};
};
const ribbonStylesFn: RibbonProps['styles'] = (info): GetProp => {
if (info.props.color === '#696FC7') {
return {
content: {
fontWeight: 'bold',
},
indicator: {
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
},
};
}
return {};
};
const App: React.FC = () => {
return (
This card has a customized ribbon with semantic classNames and styles.
This card has a customized ribbon with semantic classNames and styles.
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Badge
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| color | Customize Badge dot color | string | - | | × |
| count | Number to show in badge | ReactNode | - | | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.7.0 |
| dot | Whether to display a red dot instead of `count` | boolean | false | | × |
| offset | Set offset of the badge dot | \[number, number] | - | | × |
| overflowCount | Max count to show | number | 99 | | × |
| showZero | Whether to show badge when `count` is zero | boolean | false | | × |
| size | If `count` is set, `size` sets the size of badge | `medium` \| `small` | - | - | × |
| status | Set Badge as a status dot | `success` \| `processing` \| `default` \| `error` \| `warning` | - | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.7.0 |
| text | If `status` is set, `text` sets the display text of the status `dot` | ReactNode | - | | × |
| title | Text to show when hovering over the badge | string | - | | × |
### Badge.Ribbon
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| color | Customize Ribbon color | string | - | | × |
| placement | The placement of the Ribbon, `start` and `end` follow text direction (RTL or LTR) | `start` \| `end` | `end` | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| text | Content inside the Ribbon | ReactNode | - | | × |
## Semantic DOM
### Badge
https://ant.design/components/badge/semantic.md
### Badge.Ribbon
https://ant.design/components/badge/semantic_ribbon.md
## Design Token
## Component Token (Badge)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| dotSize | Size of dot badge | number | 6 |
| indicatorHeight | Height of badge | string \| number | 20 |
| indicatorHeightSM | Height of small badge | string \| number | 14 |
| indicatorZIndex | z-index of badge | string \| number | auto |
| paddingInline | Inline padding of multiple words badge | string \| number | 8 |
| statusSize | Size of status badge | number | 6 |
| textFontSize | Font size of badge text | number | 12 |
| textFontSizeSM | Font size of small badge text | number | 12 |
| textFontWeight | Font weight of badge text | string \| number | normal |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorBorderBg | Control the color of background border of element. | string | |
| colorError | Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. | string | |
| colorErrorHover | The hover state of the error color. | string | |
| colorInfo | Used to represent the operation information of the Token sequence, such as Alert, Tag, Progress, and other components use these map tokens. | string | |
| colorSuccess | Used to represent the token sequence of operation success, such as Result, Progress and other components will use these map tokens. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextLightSolid | Control the highlight color of text with background color, such as the text in Primary Button components. | string | |
| colorTextPlaceholder | Control the color of placeholder text. | string | |
| colorWarning | Used to represent the warning map token, such as Notification, Alert, etc. Alert or Control component(like Input) will use these map tokens. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| lineHeight | Line height of text. | number | |
| lineWidth | Border width of base components | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseOutBack | Preset motion curve. | string | |
---
## border-beam
Source: https://ant.design/components/border-beam.md
---
category: Components
group: Other
title: BorderBeam
description: Decorative component that renders a moving beam along a container border.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*uae3QbkNCm8AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*VcjGQLSrYdcAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
tag: 6.4.0
---
## When To Use
- Use when a container needs stronger visual emphasis without introducing business state semantics.
- Suitable for login panels, recommendation cards, AI modules, and key CTA blocks.
- As a decorative effect, it should not replace focus rings, validation borders, or status feedback.
## Examples
### Basic
Basic usage. Wrap any container with `BorderBeam` to add a continuous decorative beam effect along its border.
```tsx
import React from 'react';
import { BorderBeam, Card } from 'antd';
const App: React.FC = () => (
Review task status, deployment health, and recent automation activity in one panel.
);
export default App;
```
### Gradients
Display six gradient beam palettes and switch between them.
```tsx
import React from 'react';
import { BorderBeam, Card, Flex, Segmented, Tag, Typography } from 'antd';
import type { BorderBeamGradient } from 'antd';
const presets: Array<{
key: string;
name: string;
usage: string;
description: string;
color: BorderBeamGradient;
}> = [
{
key: 'ocean',
name: 'Ocean',
usage: 'Dashboard',
description: 'A calm blue-green accent that works well for data views and cloud tooling.',
color: [
{ color: '#1677ff', percent: 0 },
{ color: '#36cfc9', percent: 52 },
{ color: '#95de64', percent: 100 },
],
},
{
key: 'sunset',
name: 'Sunset',
usage: 'Upgrade',
description: 'A warm highlight for upgrade prompts, featured cards, and marketing blocks.',
color: [
{ color: '#ff7a45', percent: 0 },
{ color: '#ff4d4f', percent: 49 },
{ color: '#ff85c0', percent: 100 },
],
},
{
key: 'aurora',
name: 'Aurora',
usage: 'AI',
description:
'A vivid cool-toned beam suited for AI assistants, copilots, and automation panels.',
color: [
{ color: '#7c3aed', percent: 0 },
{ color: '#06b6d4', percent: 57 },
{ color: '#67e8f9', percent: 100 },
],
},
{
key: 'forest',
name: 'Forest',
usage: 'Recommendation',
description:
'A bright natural palette that feels good on recommendation and growth-oriented cards.',
color: [
{ color: '#22c55e', percent: 0 },
{ color: '#a3e635', percent: 54 },
{ color: '#facc15', percent: 100 },
],
},
{
key: 'ember',
name: 'Ember',
usage: 'Alert',
description: 'A high-energy warm gradient for important alerts, launch cards, and hot paths.',
color: [
{ color: '#fa541c', percent: 0 },
{ color: '#ff7875', percent: 46 },
{ color: '#ffd666', percent: 100 },
],
},
{
key: 'nebula',
name: 'Nebula',
usage: 'Labs',
description: 'A cool purple-pink mix that fits experimental modules and product lab surfaces.',
color: [
{ color: '#2f54eb', percent: 0 },
{ color: '#722ed1', percent: 44 },
{ color: '#ff85c0', percent: 100 },
],
},
];
const defaultPresetKey = presets[0].key;
const App: React.FC = () => {
const [currentPresetKey, setCurrentPresetKey] = React.useState(defaultPresetKey);
const currentPreset = presets.find((preset) => preset.key === currentPresetKey) ?? presets[0];
return (
({
label: preset.name,
value: preset.key,
}))}
value={currentPresetKey}
onChange={(value) => setCurrentPresetKey(value as string)}
/>
{currentPreset.usage}}
styles={{
body: {
display: 'flex',
flexDirection: 'column',
gap: 16,
},
}}
>
{currentPreset.description}
{currentPreset.color.map((item) => (
{item.color} · {item.percent}%
))}
Stop positions use the public 0-100 input range.
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### BorderBeam
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| children | Decorated content | `ReactNode` | - | 6.4.0 | × |
| color | Beam color configuration. Supports a single color string or gradient stops. `percent` uses the `0 ~ 100` input range and BorderBeam reserves tail space for the transparent fade | `string \| { color: string; percent: number }[]` | - | 6.4.0 | × |
| outset | Outset distance of the beam layer from the container edge. Set to `0` for clipped containers | `number \| string` | - | 6.4.0 | × |
## Design Token
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorPrimaryHover | Hover state under the main color gradient. | string | |
| lineWidth | Border width of base components | number | |
## FAQ
### How does BorderBeam behave when reduced motion is enabled? {#faq-reduced-motion}
`BorderBeam` treats the beam as a decorative effect. When `prefers-reduced-motion: reduce` is active, the beam effect is hidden.
### What does `percent` mean in `color`? {#faq-color-percent}
`percent` represents the authored stop position and accepts values from `0` to `100`. BorderBeam maps those stops into the visible beam segment and reserves the trailing area for transparent fade-out so the moving tail stays visible.
### Why is `BorderBeam` not working? {#faq-not-working}
`BorderBeam` needs to resolve the actual DOM node from `children` and insert the beam layer into that node. Make sure the wrapped content is a native DOM element, or a React component that correctly forwards its `ref` to a DOM element. Otherwise BorderBeam cannot locate the real container and the beam cannot be rendered.
The beam layer is positioned with `position: absolute`, so the resolved DOM node also needs to provide a positioning context. In most cases, set `position: relative` on the wrapped element. BorderBeam does not inspect or patch the child positioning style for you.
For performance reasons, whether `children` can host the beam and its positioning information are resolved during initialization, and are not continuously updated when the child structure or positioning styles change later.
### How do I keep the beam radius aligned with my container? {#faq-radius}
`BorderBeam` reads the computed `border-radius` from the actual container during initialization. This works best for a single-container child such as `Card`; for more complex child trees, set the radius on the actual container root for a more deterministic result.
For performance reasons, the radius is not continuously measured after the initial calculation. Later radius changes caused by size, ancestor styles, or internal child state are not guaranteed to resync automatically. The running beam may still apply internal motion smoothing.
For example:
```tsx
const radius = 24;
;
```
---
## breadcrumb
Source: https://ant.design/components/breadcrumb.md
---
category: Components
group: Navigation
title: Breadcrumb
description: Display the current location within a hierarchy. And allow going back to states higher up in the hierarchy.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*I5a2Tpqs3y0AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*Tr90QKrE_LcAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
- When the system has more than two layers in a hierarchy.
- When you need to inform the user of where they are.
- When the user may need to navigate back to a higher level.
## Examples
### Basic Usage
The simplest use.
```tsx
import React from 'react';
import { Breadcrumb } from 'antd';
const App: React.FC = () => {
return (
Application Center,
},
{
title: Application List ,
},
{
title: 'An Application',
},
]}
/>
);
};
export default App;
```
### With an Icon
The icon should be placed in front of the text.
```tsx
import React from 'react';
import { HomeOutlined, UserOutlined } from '@ant-design/icons';
import { Breadcrumb } from 'antd';
const App: React.FC = () => (
,
},
{
href: '',
title: (
<>
Application List
>
),
},
{
title: 'Application',
},
]}
/>
);
export default App;
```
### With Params
With route params.
```tsx
import React from 'react';
import { Breadcrumb } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Configuring the Separator
The separator can be customized by setting the separator property: `separator=">"`.
```tsx
import React from 'react';
import { Breadcrumb } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Bread crumbs with drop down menu
Breadcrumbs support drop down menu.
```tsx
import React from 'react';
import { Breadcrumb } from 'antd';
const menuItems = [
{
key: '1',
label: (
General
),
},
{
key: '2',
label: (
Layout
),
},
{
key: '3',
label: (
Navigation
),
},
];
const App: React.FC = () => (
Component,
},
{
title: General ,
menu: { items: menuItems },
},
{
title: 'Button',
},
]}
/>
);
export default App;
```
### Configuring the Separator Independently
Customize separator for each other.
```tsx
import React from 'react';
import { Breadcrumb } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Breadcrumb by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Breadcrumb, Flex } from 'antd';
import type { BreadcrumbProps, GetProp } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
padding: 8px;
border-radius: 4px;
`,
item: css`
color: #1890ff;
`,
separator: css`
color: rgba(0, 0, 0, 0.45);
`,
}));
const styles: BreadcrumbProps['styles'] = {
root: { border: '1px solid #f0f0f0', padding: 8, borderRadius: 4 },
item: { color: '#1890ff' },
separator: { color: 'rgba(0, 0, 0, 0.45)' },
};
const stylesFn: BreadcrumbProps['styles'] = (
info,
): GetProp => {
const items = info.props.items || [];
if (items.length > 2) {
return {
root: { border: '1px solid #F5EFFF', padding: 8, borderRadius: 4 },
item: { color: '#8F87F1' },
};
}
return {};
};
const items = [
{ title: 'Ant Design' },
{ title: Component },
{ title: 'Breadcrumb' },
];
const App: React.FC = () => {
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Breadcrumb
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | 6.0.0 | 6.0.0 |
| dropdownIcon | Custom dropdown icon | ReactNode | ` ` | 6.2.0 | 6.2.0 |
| items | The routing stack information of router (>=5.3.0 recommended, use `Breadcrumb.Item` children for older versions) | [ItemType\[\]](#itemtype) | - | 5.3.0 | × |
| itemRender | Custom item renderer, work with react-router, see [example](#use-with-browserhistory) | (route, params, routes, paths) => ReactNode | - | | × |
| params | Routing parameters | object | - | | × |
| separator | Custom separator | ReactNode | `/` | | 6.0.0 |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | 6.0.0 | 6.0.0 |
### ItemType
> type ItemType = Omit<[RouteItemType](#routeitemtype), 'title' | 'path'> | [SeparatorType](#separatortype)
### RouteItemType
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| className | The additional css class | string | - | |
| dropdownProps | The dropdown props | [Dropdown](/components/dropdown) | - | |
| href | Target of hyperlink. Can not work with `path` | string | - | |
| path | Connected path. Each path will connect with prev one. Can not work with `href` | string | - | |
| menu | The menu props | [MenuProps](/components/menu/#api) | - | 4.24.0 |
| onClick | Set the handler to handle click event | (e:MouseEvent) => void | - | |
| title | item name | ReactNode | - | 5.3.0 |
### SeparatorType
```ts
const item = {
type: 'separator', // Must have
separator: '/',
};
```
| Property | Description | Type | Default | Version |
| --------- | ----------------- | ----------- | ------- | ------- |
| type | Mark as separator | `separator` | | 5.3.0 |
| separator | Custom separator | ReactNode | `/` | 5.3.0 |
### Use with browserHistory
The link of Breadcrumb item targets `#` by default, you can use `itemRender` to make a `browserHistory` Link.
```jsx
import { Link } from 'react-router';
const items = [
{
path: '/index',
title: 'home',
},
{
path: '/first',
title: 'first',
children: [
{
path: '/general',
title: 'General',
},
{
path: '/layout',
title: 'Layout',
},
{
path: '/navigation',
title: 'Navigation',
},
],
},
{
path: '/second',
title: 'second',
},
];
function itemRender(currentRoute, params, items, paths) {
const isLast = currentRoute?.path === items[items.length - 1]?.path;
return isLast ? (
{currentRoute.title}
) : (
{currentRoute.title}
);
}
return ;
```
## Semantic DOM
https://ant.design/components/breadcrumb/semantic.md
## Design Token
## Component Token (Breadcrumb)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| iconFontSize | Icon size | number | 14 |
| itemColor | Text color of Breadcrumb item | string | rgba(0,0,0,0.45) |
| lastItemColor | Text color of the last item | string | rgba(0,0,0,0.88) |
| linkColor | Text color of link | string | rgba(0,0,0,0.45) |
| linkHoverColor | Color of hovered link | string | rgba(0,0,0,0.88) |
| separatorColor | Color of separator | string | rgba(0,0,0,0.45) |
| separatorMargin | Margin of separator | number | 8 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| colorBgTextHover | Control the background color of text in hover state. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeIcon | Control the font size of operation icon in Select, Cascader, etc. Normally same as fontSizeSM. | number | |
| lineHeight | Line height of text. | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| paddingXXS | Control the extra extra small padding of the element. | number | |
---
## button
Source: https://ant.design/components/button.md
---
category: Components
title: Button
description: To trigger an operation.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*7va7RKs3YzIAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*3T4cRqxH9-8AAAAAAAAAAAAADrJ8AQ/original
designUrl: /docs/spec/buttons
demo:
cols: 2
group:
title: General
order: 1
---
## When To Use
A button means an operation (or a series of operations). Clicking a button will trigger its corresponding business logic.
In Ant Design we provide 5 types of button.
- 🔵 Primary button: used for the main action, there can be at most one primary button in a section.
- ⚪️ Default button: used for a series of actions without priority.
- 😶 Dashed button: commonly used for adding more actions.
- 🔤 Text button: used for the most secondary action.
- 🔗 Link button: used for external links.
And 4 other properties additionally.
- 🔴 `danger`: used for actions of risk, like deletion or authorization.
- 👻 `ghost`: used in situations with complex background, home pages usually.
- 🚫 `disabled`: used when actions are not available.
- 🔃 `loading`: adds a loading spinner in button, avoids multiple submits too.
## Examples
### Syntactic sugar
Through the `type` syntactic sugar, use the preset button styles: `primary` buttons, `default` buttons, `dashed` buttons, `text` buttons, and `link` buttons.
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
const App: React.FC = () => (
Primary Button
Default Button
Dashed Button
Text Button
Link Button
);
export default App;
```
### Color & Variant
You can set the `color` and `variant` attributes at the same time can derive more variant buttons.
```tsx
import React from 'react';
import { Button, ConfigProvider, Flex } from 'antd';
import { useResponsive } from 'antd-style';
const App: React.FC = () => {
const { xxl } = useResponsive();
return (
Solid
Outlined
Dashed
Filled
Text
Link
Solid
Outlined
Dashed
Filled
Text
Link
Solid
Outlined
Dashed
Filled
Text
Link
Solid
Outlined
Dashed
Filled
Text
Link
Solid
Outlined
Dashed
Filled
Text
Link
Solid
Outlined
Dashed
Filled
Text
Link
);
};
export default App;
```
### Icon
You can add an icon using the `icon` property.
```tsx
import React from 'react';
import { SearchOutlined } from '@ant-design/icons';
import { Button, Flex, Tooltip } from 'antd';
const App: React.FC = () => (
} />
A
}>
Search
} />
}>Search
} />
}>Search
} />
}>
Search
} href="https://www.google.com" target="_blank" />
);
export default App;
```
### Icon Placement
You can set the position of a button's icon by setting the `iconPlacement` to `start` or `end` respectively.
```tsx
import React, { useState } from 'react';
import { SearchOutlined } from '@ant-design/icons';
import { Button, Divider, Flex, Radio, Space, Tooltip } from 'antd';
const App: React.FC = () => {
const [position, setPosition] = useState<'start' | 'end'>('end');
return (
<>
setPosition(e.target.value)}>
start
end
Preview
} />
A
} iconPlacement={position}>
Search
} />
} iconPlacement={position}>
Search
} />
} type="text" iconPlacement={position}>
Search
} />
} iconPlacement={position}>
Search
}
href="https://www.google.com"
target="_blank"
iconPlacement={position}
/>
Loading
>
);
};
export default App;
```
### Size
Ant Design supports three sizes of buttons: small, medium and large.
If a large or small button is desired, set the `size` property to either `large` or `small` respectively. Omit the `size` property for a button with the default `medium` size.
```tsx
import React, { useState } from 'react';
import { DownloadOutlined } from '@ant-design/icons';
import { Button, Divider, Flex, Radio } from 'antd';
import type { ConfigProviderProps } from 'antd';
type SizeType = ConfigProviderProps['componentSize'];
const App: React.FC = () => {
const [size, setSize] = useState('large'); // default is 'medium'
return (
<>
setSize(e.target.value)}>
Large
Medium
Small
Preview
Primary
Default
Dashed
Link
} size={size} />
} size={size} />
} size={size} />
} size={size}>
Download
} size={size}>
Download
>
);
};
export default App;
```
### Disabled
To mark a button as disabled, add the `disabled` property to the `Button`.
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
const App: React.FC = () => (
Primary
Primary(disabled)
Default
Default(disabled)
Dashed
Dashed(disabled)
Text
Text(disabled)
Link
Link(disabled)
Href Primary
Href Primary(disabled)
Danger Default
Danger Default(disabled)
Danger Text
Danger Text(disabled)
Danger Link
Danger Link(disabled)
Ghost
Ghost(disabled)
);
export default App;
```
### Loading
A loading indicator can be added to a button by setting the `loading` property on the `Button`. The `loading.icon` can be used to customize the loading icon.
```tsx
import React, { useState } from 'react';
import { PoweroffOutlined, SyncOutlined } from '@ant-design/icons';
import { Button, Flex } from 'antd';
const App: React.FC = () => {
const [loadings, setLoadings] = useState([]);
const enterLoading = (index: number) => {
console.log('Start loading:', index);
setLoadings((prevLoadings) => {
const newLoadings = [...prevLoadings];
newLoadings[index] = true;
return newLoadings;
});
setTimeout(() => {
setLoadings((prevLoadings) => {
const newLoadings = [...prevLoadings];
newLoadings[index] = false;
return newLoadings;
});
}, 3000);
};
return (
Loading
Loading
} loading />
}}>
Loading Icon
enterLoading(0)}>
Icon Start
enterLoading(2)}
iconPlacement="end"
>
Icon End
}
loading={loadings[1]}
onClick={() => enterLoading(1)}
>
Icon Replace
}
loading={loadings[3]}
onClick={() => enterLoading(3)}
/>
}
loading={loadings[3] && { icon: }}
onClick={() => enterLoading(3)}
>
Loading Icon
);
};
export default App;
```
### Multiple Buttons
If you need several buttons, we recommend that you use 1 primary button + n secondary buttons. If there are more than three operations, you can group some of them into a [Dropdown](/components/dropdown/#dropdown-demo-dropdown-button).
```tsx
import React from 'react';
import { EllipsisOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Button, Dropdown, Flex, Space } from 'antd';
const onMenuClick: MenuProps['onClick'] = (e) => {
console.log('click', e);
};
const items = [
{
key: '1',
label: '1st item',
},
{
key: '2',
label: '2nd item',
},
{
key: '3',
label: '3rd item',
},
];
const App: React.FC = () => (
primary
secondary
Actions
} />
);
export default App;
```
### Ghost Button
The `ghost` property will make a button's background transparent, this is commonly used in colored background.
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
const App: React.FC = () => (
Primary
Default
Dashed
Danger
);
export default App;
```
### Danger Buttons
The `danger` is a property of buttons after antd 4.0.
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
const App: React.FC = () => (
Primary
Default
Dashed
Text
Link
);
export default App;
```
### Block Button
The `block` property will make a button fit to its parent width.
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
const App: React.FC = () => (
Primary
Default
Dashed
disabled
text
Link
);
export default App;
```
### Gradient Button
Buttons with a gradient background.
```tsx
import React from 'react';
import { AntDesignOutlined } from '@ant-design/icons';
import { Button, ConfigProvider, Space } from 'antd';
import { createStyles } from 'antd-style';
const useStyle = createStyles(({ prefixCls, css }) => ({
linearGradientButton: css`
&.${prefixCls}-btn-primary:not([disabled]):not(.${prefixCls}-btn-dangerous) {
> span {
position: relative;
}
&::before {
content: '';
background: linear-gradient(135deg, #6253e1, #04befe);
position: absolute;
inset: -1px;
opacity: 1;
transition: all 0.3s;
border-radius: inherit;
}
&:hover::before {
opacity: 0;
}
}
`,
}));
const App: React.FC = () => {
const { styles } = useStyle();
return (
}>
Gradient Button
Button
);
};
export default App;
```
### Custom Wave
Wave effect brings dynamic. You can also use HappyProvider from [`@ant-design/happy-work-theme`](https://github.com/ant-design/happy-work-theme) to implement dynamic wave effect.
```tsx
import React from 'react';
import { HappyProvider } from '@ant-design/happy-work-theme';
import { Button, ConfigProvider, Flex } from 'antd';
import type { ConfigProviderProps, GetProp } from 'antd';
type WaveConfig = GetProp;
// Prepare effect holder
const createHolder = (node: HTMLElement) => {
const { borderWidth } = getComputedStyle(node);
const borderWidthNum = Number.parseInt(borderWidth, 10);
const div = document.createElement('div');
div.style.position = 'absolute';
div.style.inset = `-${borderWidthNum}px`;
div.style.borderRadius = 'inherit';
div.style.background = 'transparent';
div.style.zIndex = '999';
div.style.pointerEvents = 'none';
div.style.overflow = 'hidden';
node.appendChild(div);
return div;
};
const createDot = (holder: HTMLElement, color: string, left: number, top: number, size = 0) => {
const dot = document.createElement('div');
dot.style.position = 'absolute';
dot.style.insetInlineStart = `${left}px`;
dot.style.top = `${top}px`;
dot.style.width = `${size}px`;
dot.style.height = `${size}px`;
dot.style.borderRadius = '50%';
dot.style.background = color;
dot.style.transform = 'translate3d(-50%, -50%, 0)';
dot.style.transition = 'all 1s ease-out';
holder.appendChild(dot);
return dot;
};
// Inset Effect
const showInsetEffect: WaveConfig['showEffect'] = (node, { event, component }) => {
if (component !== 'Button') {
return;
}
const holder = createHolder(node);
const rect = holder.getBoundingClientRect();
const left = event.clientX - rect.left;
const top = event.clientY - rect.top;
const dot = createDot(holder, 'rgba(255, 255, 255, 0.65)', left, top);
// Motion
requestAnimationFrame(() => {
dot.ontransitionend = () => {
holder.remove();
};
dot.style.width = '200px';
dot.style.height = '200px';
dot.style.opacity = '0';
});
};
// Shake Effect
const showShakeEffect: WaveConfig['showEffect'] = (node, { component }) => {
if (component !== 'Button') {
return;
}
const seq = [0, -15, 15, -5, 5, 0];
const itv = 10;
let steps = 0;
const loop = () => {
cancelAnimationFrame((node as any).effectTimeout);
(node as any).effectTimeout = requestAnimationFrame(() => {
const currentStep = Math.floor(steps / itv);
const current = seq[currentStep];
const next = seq[currentStep + 1];
if (next === undefined || next === null) {
node.style.transform = '';
node.style.transition = '';
return;
}
// Trans from current to next by itv
const angle = current + ((next - current) / itv) * (steps % itv);
node.style.transform = `rotate(${angle}deg)`;
node.style.transition = 'none';
steps += 1;
loop();
});
};
loop();
};
// Component
const Wrapper: React.FC = ({ name, ...wave }) => (
{name}
);
const Demo: React.FC = () => (
Happy Work
);
export default Demo;
```
### Custom disabled backgroundColor
Customize the background color with disable (applicable to type `default` and `dashed`)
```tsx
import React from 'react';
import { Button, ConfigProvider, Flex } from 'antd';
const App: React.FC = () => (
Primary Button
Default Button
Dashed Button
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Button by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
import type { ButtonProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
root: {
border: `1px solid ${token.colorBorder}`,
borderRadius: token.borderRadius,
padding: `${token.paddingXS}px ${token.padding}px`,
height: 'auto',
},
content: {
color: token.colorText,
},
}));
const stylesObject: ButtonProps['styles'] = {
root: {
boxShadow: '0 1px 2px 0 rgba(0,0,0,0.05)',
},
};
const stylesFn: ButtonProps['styles'] = (info): GetProp => {
if (info.props.type === 'primary') {
return {
root: {
backgroundColor: '#171717',
},
content: {
color: '#fff',
},
};
}
return {};
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
return (
Object
Function
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
Different button styles generated by setting Button properties. The recommended order is: `type` -> `shape` -> `size` -> `loading` -> `disabled`.
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| autoInsertSpace | We add a space between two Chinese characters by default, which removed by setting `autoInsertSpace` to `false`. | boolean | `true` | 5.17.0 | 5.17.0 |
| block | Option to fit button width to its parent width | boolean | false | | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | 6.0.0 | 6.0.0 |
| color | Set button color | `default` \| `primary` \| `danger` \| [PresetColors](#presetcolors) | `primary` when `variant="solid"` | `default`, `primary` and `danger`: 5.21.0, `PresetColors`: 5.23.0, `solid` default color: 6.4.0 | 5.25.0 |
| danger | Syntactic sugar. Set the danger status of button. will follow `color` if provided | boolean | false | | × |
| disabled | Disabled state of button | boolean | false | | × |
| ghost | Make background transparent and invert text and border colors | boolean | false | | × |
| href | Redirect url of link button | string | - | | × |
| htmlType | Set the original html `type` of `button`, see: [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#type) | `submit` \| `reset` \| `button` | `button` | | × |
| icon | Set the icon component of button | ReactNode | - | | × |
| iconPlacement | Set the icon position of button | `start` \| `end` | `start` | - | × |
| ~~iconPosition~~ | Set the icon position of button, please use `iconPlacement` instead | `start` \| `end` | `start` | 5.17.0 | × |
| loading | Set the loading status of button | boolean \| { delay: number, icon: ReactNode } | false | icon: 5.23.0 | × |
| loadingIcon | (Only supports global configuration) Set the loading icon of button | ReactNode | ` ` | | 6.3.0 |
| onClick | Set the handler to handle `click` event | (event: React.MouseEvent) => void | - | | × |
| shape | Can be used to set button shape | `default` \| `circle` \| `round` | `default` | | 5.27.0 |
| size | Set the size of button | `large` \| `medium` \| `small` | `medium` | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | 6.0.0 | 6.0.0 |
| target | Same as target attribute of a, works when href is specified | string | - | | × |
| type | Syntactic sugar. Set button type. Will follow `variant` & `color` if provided | `primary` \| `dashed` \| `link` \| `text` \| `default` | `default` | | × |
| variant | Set button variant | `outlined` \| `dashed` \| `solid` \| `filled` \| `text` \| `link` | - | 5.21.0 | 5.25.0 |
It accepts all props which native buttons support.
### PresetColors
> type PresetColors = 'blue' | 'purple' | 'cyan' | 'green' | 'magenta' | 'pink' | 'red' | 'orange' | 'yellow' | 'volcano' | 'geekblue' | 'lime' | 'gold';
## Semantic DOM
https://ant.design/components/button/semantic.md
## Design Token
## Component Token (Button)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| contentFontSize | Font size of button content | number | 14 |
| contentFontSizeLG | Font size of large button content | number | 16 |
| contentFontSizeSM | Font size of small button content | number | 14 |
| dangerColor | Text color of danger button | string | #fff |
| dangerShadow | Shadow of danger button | string | 0 2px 0 rgba(255,38,5,0.06) |
| dashedBgDisabled | | string | rgba(0,0,0,0.04) |
| defaultActiveBg | Background color of default button when active | string | #ffffff |
| defaultActiveBorderColor | Border color of default button when active | string | #0958d9 |
| defaultActiveColor | Text color of default button when active | string | #0958d9 |
| defaultBg | Background color of default button | string | #ffffff |
| defaultBgDisabled | | string | rgba(0,0,0,0.04) |
| defaultBorderColor | Border color of default button | string | #d9d9d9 |
| defaultColor | Text color of default button | string | rgba(0,0,0,0.88) |
| defaultGhostBorderColor | Border color of default ghost button | string | #ffffff |
| defaultGhostColor | Text color of default ghost button | string | #ffffff |
| defaultHoverBg | Background color of default button when hover | string | #ffffff |
| defaultHoverBorderColor | Border color of default button | string | #4096ff |
| defaultHoverColor | Text color of default button when hover | string | #4096ff |
| defaultShadow | Shadow of default button | string | 0 2px 0 rgba(0,0,0,0.02) |
| fontWeight | Font weight of text | FontWeight \| undefined | 400 |
| ghostBg | Background color of ghost button | string | transparent |
| iconGap | Gap between icon and text | Gap \| undefined | 8 |
| linkHoverBg | Background color of link button when hover | string | transparent |
| onlyIconSize | Icon size of button which only contains icon | string \| number | inherit |
| onlyIconSizeLG | Icon size of large button which only contains icon | string \| number | inherit |
| onlyIconSizeSM | Icon size of small button which only contains icon | string \| number | inherit |
| paddingInline | Horizontal padding of button | PaddingInline \| undefined | 15 |
| paddingInlineLG | Horizontal padding of large button | PaddingInline \| undefined | 15 |
| paddingInlineSM | Horizontal padding of small button | PaddingInline \| undefined | 7 |
| primaryColor | Text color of primary button | string | #fff |
| primaryShadow | Shadow of primary button | string | 0 2px 0 rgba(5,145,255,0.1) |
| solidTextColor | Default text color for solid buttons. | string | #fff |
| textHoverBg | Background color of text button when hover | string | rgba(0,0,0,0.04) |
| textTextActiveColor | Default text color for text buttons on active | string | rgba(0,0,0,0.88) |
| textTextColor | Default text color for text buttons | string | rgba(0,0,0,0.88) |
| textTextHoverColor | Default text color for text buttons on hover | string | rgba(0,0,0,0.88) |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadius | Border radius of base components | number | |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| colorBgContainer | Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. | string | |
| colorBgContainerDisabled | Control the background color of container in disabled state. | string | |
| colorBgSolid | Solid background color, currently only used for the default solid button background color. | string | |
| colorBgSolidActive | Solid background color active state, currently only used in the active effect of the default solid button. | string | |
| colorBgSolidHover | Solid background color hover state, currently only used in the hover effect of the default solid button. | string | |
| colorError | Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. | string | |
| colorErrorActive | The active state of the error color. | string | |
| colorErrorBg | The background color of the error state. | string | |
| colorErrorBgActive | The active state background color of the error state. | string | |
| colorErrorBgFilledHover | The wrong color fills the background color of the suspension state, which is currently only used in the hover effect of the dangerous filled button. | string | |
| colorErrorHover | The hover state of the error color. | string | |
| colorFill | The darkest fill color is used to distinguish between the second and third level of fill color, and is currently only used in the hover effect of Slider. | string | |
| colorFillSecondary | The second level of fill color can outline the shape of the element more clearly, such as Rate, Skeleton, etc. It can also be used as the Hover state of the third level of fill color, such as Table, etc. | string | |
| colorFillTertiary | The third level of fill color is used to outline the shape of the element, such as Slider, Segmented, etc. If there is no emphasis requirement, it is recommended to use the third level of fill color as the default fill color. | string | |
| colorLink | Control the color of hyperlink. | string | |
| colorLinkActive | Control the color of hyperlink when clicked. | string | |
| colorLinkHover | Control the color of hyperlink when hovering. | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorPrimaryActive | Dark active state under the main color gradient. | string | |
| colorPrimaryBg | Light background color of primary color, usually used for weak visual level selection state. | string | |
| colorPrimaryBgHover | The hover state color corresponding to the light background color of the primary color. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorPrimaryHover | Hover state under the main color gradient. | string | |
| colorTextDisabled | Control the color of text in disabled state. | string | |
| colorTextLightSolid | Control the highlight color of text with background color, such as the text in Primary Button components. | string | |
| controlHeight | The height of the basic controls such as buttons and input boxes in Ant Design | number | |
| controlHeightLG | LG component height | number | |
| controlHeightSM | SM component height | number | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| lineWidth | Border width of base components | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseInOut | Preset motion curve. | string | |
| opacityLoading | Control the opacity of the loading state. | number | |
| paddingXS | Control the extra small padding of the element. | number | |
## FAQ
### How to choose type and color & variant? {#faq-type-color-variant}
Type is essentially syntactic sugar for colors and variants. It internally provides a set of mapping relationships between colors and variants for the type. If both exist at the same time, the colors and variants will be used first.
```jsx
click
```
Equivalent
```jsx
click
```
### How to close the click wave effect? {#faq-close-wave-effect}
If you don't need this feature, you can set `disabled` of `wave` in [ConfigProvider](/components/config-provider#api) as `true`.
```jsx
click
```
## Design Guide {#design-guide}
- [Where should I put my buttons!? | Ant Design 4.0 Series](https://zhuanlan.zhihu.com/p/109644406)
---
## calendar
Source: https://ant.design/components/calendar.md
---
category: Components
group: Data Display
title: Calendar
description: A container that displays data in calendar form.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*nF6_To7pDSAAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*-p-wQLik200AAAAAAAAAAAAADrJ8AQ/original
---
## When To Use
When data is in the form of dates, such as schedules, timetables, prices calendar, lunar calendar. This component also supports Year/Month switch.
## Examples
### Basic
A basic calendar component with Year/Month switch.
```tsx
import React from 'react';
import { Calendar } from 'antd';
import type { CalendarProps } from 'antd';
import type { Dayjs } from 'dayjs';
const App: React.FC = () => {
const onPanelChange = (value: Dayjs, mode: CalendarProps['mode']) => {
console.log(value.format('YYYY-MM-DD'), mode);
};
return ;
};
export default App;
```
### Notice Calendar
This component can be rendered by using `dateCellRender` and `monthCellRender` with the data you need.
```css
.events {
margin: 0;
padding: 0;
list-style: none;
}
.events .ant-badge-status {
width: 100%;
overflow: hidden;
font-size: 12px;
white-space: nowrap;
text-overflow: ellipsis;
}
.notes-month {
font-size: 28px;
text-align: center;
}
.notes-month section {
font-size: 28px;
}
```
```tsx
import React from 'react';
import type { BadgeProps, CalendarProps } from 'antd';
import { Badge, Calendar } from 'antd';
import type { Dayjs } from 'dayjs';
const getListData = (value: Dayjs) => {
let listData: { type: string; content: string }[] = []; // Specify the type of listData
switch (value.date()) {
case 8:
listData = [
{ type: 'warning', content: 'This is warning event.' },
{ type: 'success', content: 'This is usual event.' },
];
break;
case 10:
listData = [
{ type: 'warning', content: 'This is warning event.' },
{ type: 'success', content: 'This is usual event.' },
{ type: 'error', content: 'This is error event.' },
];
break;
case 15:
listData = [
{ type: 'warning', content: 'This is warning event' },
{ type: 'success', content: 'This is very long usual event......' },
{ type: 'error', content: 'This is error event 1.' },
{ type: 'error', content: 'This is error event 2.' },
{ type: 'error', content: 'This is error event 3.' },
{ type: 'error', content: 'This is error event 4.' },
];
break;
default:
}
return listData || [];
};
const getMonthData = (value: Dayjs) => {
if (value.month() === 8) {
return 1394;
}
};
const App: React.FC = () => {
const monthCellRender = (value: Dayjs) => {
const num = getMonthData(value);
return num ? (
Backlog number
) : null;
};
const dateCellRender = (value: Dayjs) => {
const listData = getListData(value);
return (
{listData.map((item) => (
))}
);
};
const cellRender: CalendarProps['cellRender'] = (current, info) => {
if (info.type === 'date') {
return dateCellRender(current);
}
if (info.type === 'month') {
return monthCellRender(current);
}
return info.originNode;
};
return ;
};
export default App;
```
### Event Range
Render event ranges across days with `cellRender`. The example calculates whether each date is the start, middle, end, or a single-day event and draws compact range bars.
```tsx
import React from 'react';
import { Calendar, theme } from 'antd';
import type { CalendarProps } from 'antd';
import { createStyles } from 'antd-style';
import { clsx } from 'clsx';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
const useStyle = createStyles(({ cssVar, css }) => {
const barRadius = 999;
const {
controlHeight,
marginXXS,
controlHeightSM,
colorTextLightSolid,
fontSizeSM,
paddingXS,
marginXS,
paddingXXS,
} = cssVar;
return {
itemContent: css`
overflow: visible;
`,
cell: css`
min-height: ${controlHeight};
`,
list: css`
display: flex;
flex-direction: column;
gap: ${marginXXS};
margin-top: ${marginXXS};
`,
bar: css`
display: block;
height: calc(${controlHeightSM} - ${marginXXS});
overflow: hidden;
color: ${colorTextLightSolid};
font-size: ${fontSizeSM};
white-space: nowrap;
text-overflow: ellipsis;
`,
barStart: css`
margin-inline-end: calc(-1 * (${paddingXS} + ${marginXS} / 2));
padding-inline-start: calc(${paddingXXS} + ${paddingXXS});
border-start-start-radius: ${barRadius}px;
border-end-start-radius: ${barRadius}px;
`,
barMiddle: css`
margin-inline: calc(-1 * (${paddingXS} + ${marginXS} / 2));
`,
barEnd: css`
margin-inline-start: calc(-1 * (${paddingXS} + ${marginXS} / 2));
border-start-end-radius: ${barRadius}px;
border-end-end-radius: ${barRadius}px;
`,
barSingle: css`
padding-inline-start: calc(${paddingXXS} + ${paddingXXS});
border-radius: ${barRadius}px;
`,
};
});
export interface CalendarEvent {
key: string;
title: string;
start: Dayjs;
end: Dayjs;
color: string;
}
const getEvents = (token: ReturnType['token']): CalendarEvent[] => [
{
key: 'release',
title: 'Release window',
start: dayjs('2026-01-08'),
end: dayjs('2026-01-10'),
color: token.colorPrimary,
},
{
key: 'design-review',
title: 'Design review',
start: dayjs('2026-01-14'),
end: dayjs('2026-01-14'),
color: token.colorSuccess,
},
{
key: 'maintenance',
title: 'Maintenance',
start: dayjs('2026-01-21'),
end: dayjs('2026-01-24'),
color: token.colorWarning,
},
{
key: 'bug-fix',
title: 'Bug fix',
start: dayjs('2026-01-30'),
end: dayjs('2026-01-31'),
color: token.colorError,
},
];
const isInRange = (current: Dayjs, event: CalendarEvent) => {
return !current.isBefore(event.start, 'day') && !current.isAfter(event.end, 'day');
};
const getRangePosition = (current: Dayjs, event: CalendarEvent) => {
const starts = current.isSame(event.start, 'day');
const ends = current.isSame(event.end, 'day');
if (starts && ends) {
return 'single';
}
if (starts) {
return 'start';
}
if (ends) {
return 'end';
}
return 'middle';
};
const App: React.FC = () => {
const { token } = theme.useToken();
const { styles } = useStyle();
const events = React.useMemo(() => getEvents(token), [token]);
const cellRender = React.useCallback['cellRender']>>(
(current, info) => {
if (info.type !== 'date') {
return null;
}
const currentEvents = events.filter((event) => isInRange(current, event));
return (
{currentEvents.map((event) => {
const position = getRangePosition(current, event);
const rangeClassName = {
start: styles.barStart,
middle: styles.barMiddle,
end: styles.barEnd,
single: styles.barSingle,
}[position];
return (
{position === 'start' || position === 'single' ? event.title : null}
);
})}
);
},
[events, styles],
);
return (
);
};
export default App;
```
### Card
Nested inside a container element for rendering in limited space.
```tsx
import React from 'react';
import { Calendar, theme } from 'antd';
import type { CalendarProps } from 'antd';
import type { Dayjs } from 'dayjs';
const onPanelChange = (value: Dayjs, mode: CalendarProps['mode']) => {
console.log(value.format('YYYY-MM-DD'), mode);
};
const App: React.FC = () => {
const { token } = theme.useToken();
const wrapperStyle: React.CSSProperties = {
width: 300,
border: `1px solid ${token.colorBorderSecondary}`,
borderRadius: token.borderRadiusLG,
};
return (
);
};
export default App;
```
### Selectable Calendar
A basic calendar component with Year/Month switch.
```tsx
import React, { useState } from 'react';
import { Alert, Calendar } from 'antd';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
const App: React.FC = () => {
const [value, setValue] = useState(() => dayjs('2017-01-25'));
const [selectedValue, setSelectedValue] = useState(() => dayjs('2017-01-25'));
const onSelect = (newValue: Dayjs) => {
setValue(newValue);
setSelectedValue(newValue);
};
const onPanelChange = (newValue: Dayjs) => {
setValue(newValue);
};
return (
<>
>
);
};
export default App;
```
### Lunar Calendar
Display lunar calendar, solar terms and other information.
```tsx
import React from 'react';
import { Calendar, Col, Radio, Row, Select } from 'antd';
import type { CalendarProps } from 'antd';
import { createStyles } from 'antd-style';
import { clsx } from 'clsx';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { HolidayUtil, Lunar } from 'lunar-typescript';
const useStyle = createStyles(({ token, css, cx }) => {
const lunar = css`
color: ${token.colorTextTertiary};
font-size: ${token.fontSizeSM}px;
`;
const weekend = css`
color: ${token.colorError};
&.gray {
opacity: 0.4;
}
`;
return {
wrapper: css`
width: 450px;
border: 1px solid ${token.colorBorderSecondary};
border-radius: ${token.borderRadiusOuter};
padding: 5px;
`,
dateCell: css`
position: relative;
&:before {
content: '';
position: absolute;
inset-inline-start: 0;
inset-inline-end: 0;
top: 0;
bottom: 0;
margin: auto;
max-width: 40px;
max-height: 40px;
background: transparent;
transition: background-color 300ms;
border-radius: ${token.borderRadiusOuter}px;
border: 1px solid transparent;
box-sizing: border-box;
}
&:hover:before {
background: ${token.controlItemBgHover};
}
`,
today: css`
&:before {
border: 1px solid ${token.colorPrimary};
}
`,
text: css`
position: relative;
z-index: 1;
`,
lunar,
current: css`
color: ${token.colorTextLightSolid};
&:before {
background: ${token.colorPrimary};
}
&:hover:before {
background: ${token.colorPrimary};
opacity: 0.8;
}
.${cx(lunar)} {
color: ${token.colorTextLightSolid};
opacity: 0.9;
}
.${cx(weekend)} {
color: ${token.colorTextLightSolid};
}
`,
monthCell: css`
width: 120px;
color: ${token.colorTextBase};
border-radius: ${token.borderRadiusOuter}px;
padding: 5px 0;
&:hover {
background: ${token.controlItemBgHover};
}
`,
monthCellCurrent: css`
color: ${token.colorTextLightSolid};
background: ${token.colorPrimary};
&:hover {
background: ${token.colorPrimary};
opacity: 0.8;
}
`,
weekend,
};
});
const App: React.FC = () => {
const { styles } = useStyle({ test: true });
const [selectDate, setSelectDate] = React.useState(() => dayjs());
const [panelDate, setPanelDate] = React.useState(() => dayjs());
const onPanelChange = (value: Dayjs, mode: CalendarProps['mode']) => {
console.log(value.format('YYYY-MM-DD'), mode);
setPanelDate(value);
};
const onDateChange: CalendarProps['onSelect'] = (value) => {
setSelectDate(value);
};
const cellRender: CalendarProps['fullCellRender'] = (date, info) => {
const d = Lunar.fromDate(date.toDate());
const lunar = d.getDayInChinese();
const solarTerm = d.getJieQi();
const isWeekend = date.day() === 6 || date.day() === 0;
const h = HolidayUtil.getHoliday(date.get('year'), date.get('month') + 1, date.get('date'));
const displayHoliday = h?.getTarget() === h?.getDay() ? h?.getName() : undefined;
if (info.type === 'date') {
return React.cloneElement(info.originNode, {
...(info.originNode as React.ReactElement).props,
className: clsx(styles.dateCell, {
[styles.current]: selectDate.isSame(date, 'date'),
[styles.today]: date.isSame(dayjs(), 'date'),
}),
children: (
{date.get('date')}
{info.type === 'date' && (
{displayHoliday || solarTerm || lunar}
)}
),
});
}
if (info.type === 'month') {
// Due to the fact that a solar month is part of the lunar month X and part of the lunar month X+1,
// when rendering a month, always take X as the lunar month of the month
const d2 = Lunar.fromDate(new Date(date.get('year'), date.get('month')));
const month = d2.getMonthInChinese();
return (
{date.get('month') + 1}月({month}月)
);
}
};
const getYearLabel = (year: number) => {
const d = Lunar.fromDate(new Date(year + 1, 0));
return `${d.getYearInChinese()}年(${d.getYearInGanZhi()}${d.getYearShengXiao()}年)`;
};
const getMonthLabel = (month: number, value: Dayjs) => {
const d = Lunar.fromDate(new Date(value.year(), month));
const lunar = d.getMonthInChinese();
return `${month + 1}月(${lunar}月)`;
};
return (
{
const start = 0;
const end = 12;
const monthOptions = [];
let current = value.clone();
const localeData = value.localeData();
const months = [];
for (let i = 0; i < 12; i++) {
current = current.month(i);
months.push(localeData.monthsShort(current));
}
for (let i = start; i < end; i++) {
monthOptions.push({
label: getMonthLabel(i, value),
value: i,
});
}
const year = value.year();
const month = value.month();
const options = [];
for (let i = year - 10; i < year + 10; i += 1) {
options.push({
label: getYearLabel(i),
value: i,
});
}
return (
{
const now = value.clone().year(newYear);
onChange(now);
}}
/>
{
const now = value.clone().month(newMonth);
onChange(now);
}}
/>
onTypeChange(e.target.value)}
value={type}
>
月
年
);
}}
/>
);
};
export default App;
```
### Show Week
Show week number in fullscreen calendar by setting `showWeek` prop to `true`.
```tsx
import React from 'react';
import { Calendar } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### Customize Header
Customize Calendar header content.
```tsx
import React from 'react';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { Calendar, Flex, Radio, Select, theme, Typography } from 'antd';
import type { CalendarProps } from 'antd';
import type { Dayjs } from 'dayjs';
import dayLocaleData from 'dayjs/plugin/localeData';
dayjs.extend(dayLocaleData);
const App: React.FC = () => {
const { token } = theme.useToken();
const onPanelChange = (value: Dayjs, mode: CalendarProps['mode']) => {
console.log(value.format('YYYY-MM-DD'), mode);
};
const wrapperStyle: React.CSSProperties = {
width: 300,
border: `1px solid ${token.colorBorderSecondary}`,
borderRadius: token.borderRadiusLG,
};
return (
{
const year = value.year();
const month = value.month();
const yearOptions = Array.from({ length: 20 }, (_, i) => {
const label = year - 10 + i;
return { label, value: label };
});
const monthOptions = value
.localeData()
.monthsShort()
.map((label, index) => ({
label,
value: index,
}));
return (
Custom header
onTypeChange(e.target.value)}
value={type}
>
Month
Year
{
const now = value.clone().year(newYear);
onChange(now);
}}
/>
{
const now = value.clone().month(newMonth);
onChange(now);
}}
/>
);
}}
onPanelChange={onPanelChange}
/>
);
};
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Calendar by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Calendar, Flex } from 'antd';
import type { CalendarProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
import type { Dayjs } from 'dayjs';
const useStyles = createStyles(({ token }) => ({
root: {
padding: 10,
backgroundColor: token.colorPrimaryBg,
},
}));
const stylesObject: CalendarProps['styles'] = {
root: {
borderRadius: 8,
width: 600,
},
};
const stylesFunction: CalendarProps['styles'] = (
info,
): GetProp, 'styles', 'Return'> => {
if (info.props.fullscreen) {
return {
root: {
border: '2px solid #BDE3C3',
borderRadius: 10,
backgroundColor: 'rgba(189,227,195, 0.3)',
},
};
}
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
**Note:** Part of the Calendar's locale is read from `value`. So, please set the locale of `dayjs` correctly.
```jsx
// The default locale is en-US, if you want to use other locale, just set locale in entry file globally.
// import dayjs from 'dayjs';
// import 'dayjs/locale/zh-cn';
// dayjs.locale('zh-cn');
```
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| cellRender | Customize cell content | function(current: dayjs, info: { prefixCls: string, originNode: React.ReactElement, today: dayjs, range?: 'start' \| 'end', type: PanelMode, locale?: Locale, subType?: 'hour' \| 'minute' \| 'second' \| 'meridiem' }) => React.ReactNode | - | 5.4.0 | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| ~~dateFullCellRender~~ | Customize the display of the date cell, the returned content will override the cell. Please use `fullCellRender` instead in 5.4.0 and later | function(date: Dayjs): ReactNode | - | < 5.4.0 | × |
| fullCellRender | Customize cell content | function(current: dayjs, info: { prefixCls: string, originNode: React.ReactElement, today: dayjs, range?: 'start' \| 'end', type: PanelMode, locale?: Locale, subType?: 'hour' \| 'minute' \| 'second' \| 'meridiem' }) => React.ReactNode | - | 5.4.0 | × |
| defaultValue | The date selected by default | [dayjs](https://day.js.org/) | - | | × |
| disabledDate | Function that specifies the dates that cannot be selected, `currentDate` is same dayjs object as `value` prop which you shouldn't mutate it (https://github.com/ant-design/ant-design/issues/30987) | (currentDate: Dayjs) => boolean | - | | × |
| fullscreen | Whether to display in full-screen | boolean | true | | × |
| showWeek | Whether to display week number | boolean | false | 5.23.0 | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| headerRender | Render custom header in panel | function(object:{value: Dayjs, type: 'year' \| 'month', onChange: f(), onTypeChange: f()}) | - | | × |
| locale | The calendar's locale | object | [(default)](https://github.com/ant-design/ant-design/blob/master/components/date-picker/locale/example.json) | | × |
| mode | The display mode of the calendar | `month` \| `year` | `month` | | × |
| validRange | To set valid range | \[[dayjs](https://day.js.org/), [dayjs](https://day.js.org/)] | - | | × |
| value | The current selected date | [dayjs](https://day.js.org/) | - | | × |
| onChange | Callback for when date changes | function(date: Dayjs) | - | | × |
| onPanelChange | Callback for when panel changes | function(date: Dayjs, mode: string) | - | | × |
| onSelect | Callback for when a date is selected, include source info | function(date: Dayjs, info: { source: 'year' \| 'month' \| 'date' \| 'customize' }) | - | `info`: 5.6.0 | × |
## Semantic DOM
https://ant.design/components/calendar/semantic.md
## Design Token
## Component Token (Calendar)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| fullBg | Background color of full calendar | string | #ffffff |
| fullPanelBg | Background color of full calendar panel | string | #ffffff |
| itemActiveBg | Background color of selected date item | string | #e6f4ff |
| miniContentHeight | Height of mini calendar content | string \| number | 256 |
| monthControlWidth | Width of month select | string \| number | 70 |
| yearControlWidth | Width of year select | string \| number | 80 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| colorBgContainer | Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. | string | |
| colorFillSecondary | The second level of fill color can outline the shape of the element more clearly, such as Rate, Skeleton, etc. It can also be used as the Hover state of the third level of fill color, such as Table, etc. | string | |
| colorIcon | Weak action. Such as `allowClear` or Alert close button | string | |
| colorIconHover | Weak action hover color. Such as `allowClear` or Alert close button | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorSplit | Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDisabled | Control the color of text in disabled state. | string | |
| colorTextHeading | Control the font color of heading. | string | |
| colorTextLightSolid | Control the highlight color of text with background color, such as the text in Primary Button components. | string | |
| colorTextTertiary | The third level of text color is generally used for descriptive text, such as form supplementary explanation text, list descriptive text, etc. | string | |
| controlHeightLG | LG component height | number | |
| controlHeightSM | SM component height | number | |
| controlItemBgActive | Control the background color of control component item when active. | string | |
| controlItemBgHover | Control the background color of control component item when hovering. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontWeightStrong | Control the font weight of heading components (such as h1, h2, h3) or selected item. | number | |
| lineHeight | Line height of text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| lineWidthBold | The default line width of the outline class components, such as Button, Input, Select, etc. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| padding | Control the padding of the element. | number | |
| paddingSM | Control the small padding of the element. | number | |
| paddingXS | Control the extra small padding of the element. | number | |
| paddingXXS | Control the extra extra small padding of the element. | number | |
| screenXS | Control the screen width of extra small screens. | number | |
## FAQ
### How to use Calendar with customize date library? {#faq-customize-date-library}
See [Use custom date library](/docs/react/use-custom-date-library#calendar)
### How to set locale for date-related components? {#faq-set-locale-date-components}
See [How to set locale for date-related components](/components/date-picker/#localization)
### Date-related components locale is not working? {#faq-locale-not-working}
See FAQ [Date-related-components-locale-is-not-working?](/docs/react/faq#date-related-components-locale-is-not-working)
### How to get date from panel click? {#faq-get-date-panel-click}
`onSelect` provide `info.source` to help on this:
```tsx
{
if (source === 'date') {
console.log('Panel Select:', source);
}
}}
/>
```
---
## card
Source: https://ant.design/components/card.md
---
category: Components
group: Data Display
title: Card
description: A container for displaying information.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*QXO1SKEdIzYAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*5WDvQp_H7LUAAAAAAAAAAAAADrJ8AQ/original
---
## When To Use
A card can be used to display content related to a single subject. The content can consist of multiple elements of varying types and sizes.
## Examples
### Basic card
A basic card containing a title, content and an extra corner content. Supports two sizes: `medium` and `small`.
```tsx
import React from 'react';
import { Card, Space } from 'antd';
const App: React.FC = () => (
More} style={{ width: 300 }}>
Card content
Card content
Card content
More} style={{ width: 300 }}>
Card content
Card content
Card content
);
export default App;
```
### No border
A borderless card on a gray background.
```tsx
import React from 'react';
import { Card } from 'antd';
const App: React.FC = () => (
Card content
Card content
Card content
);
export default App;
```
### Simple card
A simple card only containing a content area.
```tsx
import React from 'react';
import { Card } from 'antd';
const App: React.FC = () => (
Card content
Card content
Card content
);
export default App;
```
### Customized content
You can use `Card.Meta` to support more flexible content.
```tsx
import React from 'react';
import { Card } from 'antd';
const { Meta } = Card;
const App: React.FC = () => (
}
>
);
export default App;
```
### Card in column
Cards usually cooperate with grid column layout in overview page.
```tsx
import React from 'react';
import { Card, Col, Row } from 'antd';
const App: React.FC = () => (
Card content
Card content
Card content
);
export default App;
```
### Loading card
Shows a loading indicator while the contents of the card is being fetched.
```tsx
import React, { useState } from 'react';
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import { Avatar, Card, Flex, Switch } from 'antd';
const actions: React.ReactNode[] = [
,
,
,
];
const App: React.FC = () => {
const [loading, setLoading] = useState(true);
return (
setLoading(!checked)} />
}
title="Card title"
description={
<>
This is the description
This is the description
>
}
/>
}
title="Card title"
description={
<>
This is the description
This is the description
>
}
/>
);
};
export default App;
```
### Grid card
Grid style card content.
```tsx
import React from 'react';
import { Card } from 'antd';
const gridStyle: React.CSSProperties = {
width: '25%',
textAlign: 'center',
};
const App: React.FC = () => (
Content
Content
Content
Content
Content
Content
Content
);
export default App;
```
### Inner card
It can be placed inside the ordinary card to display the information of the multilevel structure.
```tsx
import React from 'react';
import { Card } from 'antd';
const App: React.FC = () => (
More}>
Inner Card content
More}
>
Inner Card content
);
export default App;
```
### With tabs
More content can be hosted.
```tsx
import React, { useState } from 'react';
import { Card } from 'antd';
const tabList = [
{
key: 'tab1',
tab: 'tab1',
},
{
key: 'tab2',
tab: 'tab2',
},
];
const contentList: Record = {
tab1: content1
,
tab2: content2
,
};
const tabListNoTitle = [
{
key: 'article',
label: 'article',
},
{
key: 'app',
label: 'app',
},
{
key: 'project',
label: 'project',
},
];
const contentListNoTitle: Record = {
article: article content
,
app: app content
,
project: project content
,
};
const App: React.FC = () => {
const [activeTabKey1, setActiveTabKey1] = useState('tab1');
const [activeTabKey2, setActiveTabKey2] = useState('app');
const onTab1Change = (key: string) => {
setActiveTabKey1(key);
};
const onTab2Change = (key: string) => {
setActiveTabKey2(key);
};
return (
<>
More}
tabList={tabList}
activeTabKey={activeTabKey1}
onTabChange={onTab1Change}
>
{contentList[activeTabKey1]}
More}
onTabChange={onTab2Change}
tabProps={{ size: 'medium' }}
>
{contentListNoTitle[activeTabKey2]}
>
);
};
export default App;
```
### Support more content configuration
A Card that supports `cover`, `avatar`, `title` and `description`.
```tsx
import React from 'react';
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import { Avatar, Card } from 'antd';
const { Meta } = Card;
const App: React.FC = () => (
}
actions={[
,
,
,
]}
>
}
title="Card title"
description="This is the description"
/>
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Card by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { EditOutlined, HeartOutlined, ShareAltOutlined } from '@ant-design/icons';
import { Avatar, Button, Card, Flex } from 'antd';
import type { CardMetaProps, CardProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
const { Meta } = Card;
const useStyles = createStyles(({ token }) => ({
root: {
width: 300,
backgroundColor: token.colorBgContainer,
borderRadius: token.borderRadius,
boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
border: `1px solid ${token.colorBorderSecondary}`,
},
header: {
borderBottom: 'none',
paddingBottom: 8,
},
body: {
paddingTop: 0,
},
}));
const stylesCard: CardProps['styles'] = {
root: {
boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
borderRadius: 8,
},
title: {
fontSize: 16,
fontWeight: 500,
},
};
const stylesCardFn: CardProps['styles'] = (info): GetProp => {
if (info.props.variant === 'outlined') {
return {
root: {
borderColor: '#696FC7',
boxShadow: '0 2px 8px #A7AAE1',
borderRadius: 8,
},
extra: {
color: '#696FC7',
},
title: {
fontSize: 16,
fontWeight: 500,
color: '#A7AAE1',
},
};
}
};
const stylesCardMeta: CardMetaProps['styles'] = {
title: {
color: '#A7AAE1',
},
description: {
color: '#A7AAE1',
},
};
const actions = [
,
,
,
];
const App: React.FC = () => {
const { styles: classNames } = useStyles();
const sharedCardProps: CardProps = {
classNames,
actions,
};
const sharedCardMetaProps: CardMetaProps = {
avatar: ,
description: 'This is the description',
};
return (
More}
variant="borderless"
>
More
}
>
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
```jsx
Card content
```
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| actions | The action list, shows at the bottom of the Card | Array<ReactNode> | - | | × |
| activeTabKey | Current TabPane's key | string | - | | × |
| ~~bordered~~ | Toggles rendering of the border around the card, please use `variant` instead | boolean | true | | × |
| ~~bodyStyle~~ | Style of card body, please use `styles.body` instead | CSSProperties | - | - | × |
| variant | Variants of Card | `outlined` \| `borderless` | `outlined` | 5.24.0 | 5.24.0 |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.14.0 |
| cover | Card cover | ReactNode | - | | × |
| defaultActiveTabKey | Initial active TabPane's key, if `activeTabKey` is not set | string | `The key of first tab` | | × |
| extra | Content to render in the top-right corner of the card | ReactNode | - | | × |
| hoverable | Lift up when hovering card | boolean | false | | × |
| ~~headStyle~~ | Style of card head, please use `styles.header` instead | CSSProperties | - | - | × |
| loading | Shows a loading indicator while the contents of the card are being fetched | boolean | false | | × |
| size | Size of card | `medium` \| `small` | `medium` | | × |
| tabBarExtraContent | Extra content in tab bar | ReactNode | - | | × |
| tabList | List of TabPane's head | [TabItemType](/components/tabs#tabitemtype)[] | - | | × |
| tabProps | [Tabs](/components/tabs/#tabs) | - | - | | × |
| title | Card title | ReactNode | - | | × |
| type | Card style type, can be set to `inner` or not set | string | - | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.14.0 |
| onTabChange | Callback when tab is switched | (key) => void | - | | × |
### Card.Grid
| Property | Description | Type | Default | Version |
| --------- | ------------------------------- | ------- | ------- | ------- |
| hoverable | Lift up when hovering card grid | boolean | true | |
### Card.Meta
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| avatar | Avatar or icon | ReactNode | - | | × |
| description | Description content | ReactNode | - | | × |
| title | Title content | ReactNode | - | | × |
## Semantic DOM
### Card
https://ant.design/components/card/semantic.md
### Card.Meta
https://ant.design/components/card/semantic_meta.md
## Design Token
## Component Token (Card)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| actionsBg | Background color of card actions | string | #ffffff |
| actionsLiMargin | Margin of each item in card actions | string | 12px 0 |
| bodyPadding | Padding of card body | number | 24 |
| bodyPaddingSM | Padding of small card body | number | 12 |
| extraColor | Text color of extra area | string | rgba(0,0,0,0.88) |
| headerBg | Background color of card header | string | transparent |
| headerFontSize | Font size of card header | string \| number | 16 |
| headerFontSizeSM | Font size of small card header | string \| number | 14 |
| headerHeight | Height of card header | string \| number | 56 |
| headerHeightSM | Height of small card header | string \| number | 38 |
| headerPadding | Padding of card head | number | 24 |
| headerPaddingSM | Padding of small card head | number | 12 |
| tabsMarginBottom | Margin bottom of tabs component | number | -17 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| boxShadowTertiary | Control the tertiary box shadow style of an element. | string | |
| colorBgContainer | Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. | string | |
| colorBorderSecondary | Slightly lighter than the default border color, this color is the same as `colorSplit`. Solid color is used. | string | |
| colorFillAlter | Control the alternative background color of element. | string | |
| colorIcon | Weak action. Such as `allowClear` or Alert close button | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDescription | Control the font color of text description. | string | |
| colorTextHeading | Control the font color of heading. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeLG | Large font size | number | |
| fontWeightStrong | Control the font weight of heading components (such as h1, h2, h3) or selected item. | number | |
| lineHeight | Line height of text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| padding | Control the padding of the element. | number | |
| paddingLG | Control the large padding of the element. | number | |
---
## carousel
Source: https://ant.design/components/carousel.md
---
category: Components
group: Data Display
title: Carousel
description: A set of carousel areas.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*bPMSSqbaTMkAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*a-58QpYnqOsAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
- When there is a group of content on the same level.
- When there is insufficient content space, it can be used to save space in the form of a revolving door.
- Commonly used for a group of pictures/cards.
## Examples
### Basic
Basic usage.
```tsx
import React from 'react';
import { Carousel } from 'antd';
const contentStyle: React.CSSProperties = {
margin: 0,
height: '160px',
color: '#fff',
lineHeight: '160px',
textAlign: 'center',
background: '#364d79',
};
const App: React.FC = () => {
const onChange = (currentSlide: number) => {
console.log(currentSlide);
};
return (
1
2
3
4
);
};
export default App;
```
### Position
There are 4 position options available.
```tsx
import React, { useState } from 'react';
import type { CarouselProps, RadioChangeEvent } from 'antd';
import { Carousel, Radio } from 'antd';
type DotPlacement = CarouselProps['dotPlacement'];
const contentStyle: React.CSSProperties = {
margin: 0,
height: '160px',
color: '#fff',
lineHeight: '160px',
textAlign: 'center',
background: '#364d79',
};
const App: React.FC = () => {
const [dotPlacement, setDotPlacement] = useState('top');
const handlePositionChange = ({ target: { value } }: RadioChangeEvent) => {
setDotPlacement(value);
};
return (
<>
Top
Bottom
Start
End
1
2
3
4
>
);
};
export default App;
```
### Scroll automatically
Timing of scrolling to the next card/picture.
```tsx
import React from 'react';
import { Carousel } from 'antd';
const contentStyle: React.CSSProperties = {
margin: 0,
height: '160px',
color: '#fff',
lineHeight: '160px',
textAlign: 'center',
background: '#364d79',
};
const App: React.FC = () => (
1
2
3
4
);
export default App;
```
### Fade in
Slides use fade for transition.
```tsx
import React from 'react';
import { Carousel } from 'antd';
const contentStyle: React.CSSProperties = {
margin: 0,
height: '160px',
color: '#fff',
lineHeight: '160px',
textAlign: 'center',
background: '#364d79',
};
const App: React.FC = () => (
1
2
3
4
);
export default App;
```
### Arrows for switching
Show the arrows for switching.
```tsx
import React from 'react';
import { Carousel } from 'antd';
const contentStyle: React.CSSProperties = {
margin: 0,
height: '160px',
color: '#fff',
lineHeight: '160px',
textAlign: 'center',
background: '#364d79',
};
const App: React.FC = () => (
<>
1
2
3
4
1
2
3
4
>
);
export default App;
```
### Progress of dots
Show progress of dots.
```tsx
import React from 'react';
import { Carousel } from 'antd';
const contentStyle: React.CSSProperties = {
margin: 0,
height: '160px',
color: '#fff',
lineHeight: '160px',
textAlign: 'center',
background: '#364d79',
};
const App: React.FC = () => (
1
2
3
4
);
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| arrows | Whether to show switch arrows | boolean | false | 5.17.0 | × |
| autoplay | Whether to scroll automatically, you can specify `autoplay={{ dotDuration: true }}` to display the progress bar | boolean \| { dotDuration?: boolean } | false | dotDuration: 5.24.0 | × |
| autoplaySpeed | Delay between each auto scroll (in milliseconds) | number | 3000 | | × |
| adaptiveHeight | Adjust the slide's height automatically | boolean | false | | × |
| dotPlacement | The position of the dots, which can be one of `top` `bottom` `start` `end` | string | `bottom` | | × |
| ~~dotPosition~~ | The position of the dots, which can be one of `top` `bottom` `left` `right` `start` `end`, Please use `dotPlacement` instead | string | `bottom` | | × |
| dots | Whether to show the dots at the bottom of the gallery, `object` for `dotsClass` | boolean \| { className?: string } | true | | × |
| draggable | Enable scrollable via dragging on desktop | boolean | false | | × |
| fade | Whether to use fade transition | boolean | false | | × |
| infinite | Infinitely wrap around contents | boolean | true | | × |
| speed | Animation speed in milliseconds | number | 500 | | × |
| easing | Transition interpolation function name | string | `linear` | | × |
| effect | Transition effect | `scrollx` \| `fade` | `scrollx` | | × |
| afterChange | Callback function called after the current index changes | (current: number) => void | - | | × |
| beforeChange | Callback function called before the current index changes | (current: number, next: number) => void | - | | × |
| waitForAnimate | Whether to wait for the animation when switching | boolean | false | | × |
Find more APIs in react-slick [documentation](https://react-slick.neostack.com/docs/api).
## Methods
| Name | Description |
| --- | --- |
| goTo(slideNumber, dontAnimate) | Go to slide index, if dontAnimate=true, it happens without animation |
| next() | Change current slide to next slide |
| prev() | Change current slide to previous slide |
## Design Token
## Component Token (Carousel)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| arrowOffset | arrows offset to Carousel edge | number | 8 |
| arrowSize | Size of arrows | number | 16 |
| dotActiveWidth | Width of active indicator | string \| number | 24 |
| dotGap | gap between indicator | number | 4 |
| dotHeight | Height of indicator | string \| number | 3 |
| dotOffset | dot offset to Carousel edge | number | 12 |
| dotWidth | Width of indicator | string \| number | 16 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorBgContainer | Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| lineHeight | Line height of text. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
## FAQ
### How to add custom arrows? {#faq-add-custom-arrows}
See [#12479](https://github.com/ant-design/ant-design/issues/12479).
---
## cascader
Source: https://ant.design/components/cascader.md
---
category: Components
group: Data Entry
title: Cascader
description: Cascade selection box.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*ngTnQZNOcK0AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*Nt8xR7afyr0AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
- When you need to select from a set of associated data set. Such as province/city/district, company level, things classification.
- When selecting from a large data set, with multi-stage classifications separated for easy selection.
- Chooses cascade items in one float layer for better user experience.
## Examples
### Basic
Cascade selection box for selecting province/city/district.
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
import type { HTMLAriaDataAttributes } from 'antd/es/_util/aria-data-attrs';
type Option = {
value: string;
label: string;
children?: Option[];
} & HTMLAriaDataAttributes;
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
'aria-label': 'Zhejiang',
'data-title': 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
'aria-label': 'Hangzhou',
'data-title': 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
'aria-label': 'West Lake',
'data-title': 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
'aria-label': 'Jiangsu',
'data-title': 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
'aria-label': 'Nanjing',
'data-title': 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
'aria-label': 'Zhong Hua Men',
'data-title': 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => (
);
export default App;
```
### Default value
Specifies default value by an array.
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => (
);
export default App;
```
### Custom trigger
Separate trigger button and result.
```tsx
import React, { useState } from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
},
],
},
];
const App: React.FC = () => {
const [text, setText] = useState('Unselect');
const onChange: CascaderProps ['onChange'] = (_, selectedOptions) => {
setText(selectedOptions.map((o) => o.label).join(', '));
};
return (
{text}
Change city
);
};
export default App;
```
### Hover
Hover to expand sub menu, click to select option.
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
// Just show the latest item.
const displayRender = (labels: string[]) => labels[labels.length - 1];
const App: React.FC = () => (
);
export default App;
```
### Disabled option
Disable option by specifying the `disabled` property in `options`.
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string;
label: string;
disabled?: boolean;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
disabled: true,
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => ;
export default App;
```
### Change on select
Allows the selection of only parent options.
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hanzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => ;
export default App;
```
### Multiple
Select multiple options. Disable the `checkbox` by adding the `disableCheckbox` property and selecting a specific item. The style of the disable can be modified by the className.
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string | number;
label: string;
children?: Option[];
disableCheckbox?: boolean;
}
const options: Option[] = [
{
label: 'Light',
value: 'light',
children: Array.from({ length: 20 }).map((_, index) => ({
label: `Number ${index}`,
value: index,
})),
},
{
label: 'Bamboo',
value: 'bamboo',
children: [
{
label: 'Little',
value: 'little',
children: [
{
label: 'Toy Fish',
value: 'fish',
disableCheckbox: true,
},
{
label: 'Toy Cards',
value: 'cards',
},
{
label: 'Toy Bird',
value: 'bird',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => (
);
export default App;
```
### ShowCheckedStrategy
Shows a selected item in a box using `showCheckedStrategy`.
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
const { SHOW_CHILD } = Cascader;
interface Option {
value: string | number;
label: string;
children?: Option[];
}
const options: Option[] = [
{
label: 'Light',
value: 'light',
children: Array.from({ length: 20 }).map((_, index) => ({
label: `Number ${index}`,
value: index,
})),
},
{
label: 'Bamboo',
value: 'bamboo',
children: [
{
label: 'Little',
value: 'little',
children: [
{
label: 'Toy Fish',
value: 'fish',
},
{
label: 'Toy Cards',
value: 'cards',
},
{
label: 'Toy Bird',
value: 'bird',
},
],
},
],
},
];
const App: React.FC = () => {
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
return (
<>
>
);
};
export default App;
```
### Size
Cascade selection box of different sizes.
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => (
<>
>
);
export default App;
```
### Custom render
For instance, add an external link after the selected value.
```tsx
import React from 'react';
import { Cascader } from 'antd';
import type { CascaderProps, GetProp } from 'antd';
type DefaultOptionType = GetProp[number];
interface Option {
value: string;
label: string;
children?: Option[];
code?: number;
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
code: 752100,
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
code: 453400,
},
],
},
],
},
];
const handleAreaClick = (
e: React.MouseEvent,
label: string,
option: DefaultOptionType,
) => {
e.stopPropagation();
console.log('clicked', label, option);
};
const displayRender: CascaderProps['displayRender'] = (labels, selectedOptions = []) =>
labels.map((label, i) => {
const option = selectedOptions[i];
if (i === labels.length - 1) {
return (
{label} ( handleAreaClick(e, label, option)}>{option.code} )
);
}
return {label} / ;
});
const App: React.FC = () => (
(
<>
{option.label} ({option.value})
>
)}
/>
);
export default App;
```
### Search
Search and select options directly.
> Now, `Cascader[showSearch]` doesn't support search on server, more info [#5547](https://github.com/ant-design/ant-design/issues/5547)
```tsx
import React from 'react';
import { Cascader } from 'antd';
import type { CascaderProps, GetProp } from 'antd';
type DefaultOptionType = GetProp[number];
interface Option {
value: string;
label: string;
children?: Option[];
disabled?: boolean;
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
{
value: 'xiasha',
label: 'Xia Sha',
disabled: true,
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua men',
},
],
},
],
},
];
const onChange: CascaderProps['onChange'] = (value, selectedOptions) => {
console.log(value, selectedOptions);
};
const filter = (inputValue: string, path: DefaultOptionType[]) =>
path.some((option) => (option.label as string).toLowerCase().includes(inputValue.toLowerCase()));
const App: React.FC = () => (
console.log(value) }}
/>
);
export default App;
```
### Load Options Lazily
Load options lazily with `loadData`.
> Note: `loadData` cannot work with `showSearch`.
```tsx
import React, { useState } from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value?: string | number | null;
label: React.ReactNode;
children?: Option[];
isLeaf?: boolean;
}
const optionLists: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
isLeaf: false,
},
{
value: 'jiangsu',
label: 'Jiangsu',
isLeaf: false,
},
];
const App: React.FC = () => {
const [options, setOptions] = useState(optionLists);
const onChange: CascaderProps ['onChange'] = (value, selectedOptions) => {
console.log(value, selectedOptions);
};
const loadData = (selectedOptions: Option[]) => {
const targetOption = selectedOptions[selectedOptions.length - 1];
// load options lazily
setTimeout(() => {
targetOption.children = [
{
label: `${targetOption.label} Dynamic 1`,
value: 'dynamic1',
},
{
label: `${targetOption.label} Dynamic 2`,
value: 'dynamic2',
},
];
setOptions([...options]);
}, 1000);
};
return ;
};
export default App;
```
### Custom Field Names
Custom field names.
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
code: string;
name: string;
items?: Option[];
}
const options: Option[] = [
{
code: 'zhejiang',
name: 'Zhejiang',
items: [
{
code: 'hangzhou',
name: 'Hangzhou',
items: [
{
code: 'xihu',
name: 'West Lake',
},
],
},
],
},
{
code: 'jiangsu',
name: 'Jiangsu',
items: [
{
code: 'nanjing',
name: 'Nanjing',
items: [
{
code: 'zhonghuamen',
name: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => (
);
export default App;
```
### Prefix and Suffix
Use `prefix` to customize the prefix content, use `suffixIcon` to customize the selection box suffix icon, and use `expandIcon` to customize the current item expand icon.
```tsx
import React from 'react';
import { SmileOutlined } from '@ant-design/icons';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => (
<>
}
options={options}
onChange={onChange}
placeholder="Please select"
/>
}
options={options}
onChange={onChange}
placeholder="Please select"
/>
}
options={options}
onChange={onChange}
placeholder="Please select"
/>
>
);
export default App;
```
### Custom dropdown
Customize the dropdown menu via `popupRender`.
```tsx
import React from 'react';
import { Cascader, Divider } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const popupRender = (menus: React.ReactNode) => (
{menus}
The footer is not very short.
);
const App: React.FC = () => (
);
export default App;
```
### Placement
You can manually specify the position of the popup via `placement`.
```tsx
import React, { useState } from 'react';
import type { RadioChangeEvent } from 'antd';
import { Cascader, Radio } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const App: React.FC = () => {
const [placement, setPlacement] = useState<'bottomLeft' | 'bottomRight' | 'topLeft' | 'topRight'>(
'topLeft',
);
const placementChange = (e: RadioChangeEvent) => {
setPlacement(e.target.value);
};
return (
<>
topLeft
topRight
bottomLeft
bottomRight
>
);
};
export default App;
```
### Variants
Variants of Cascader, there are four variants: `outlined` `filled` `borderless` and `underlined`.
```tsx
import React from 'react';
import { Cascader, Flex } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Status
Add status to Cascader with `status`, which could be `error` or `warning`.
```tsx
import React from 'react';
import { Cascader, Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Cascader by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Cascader, Flex } from 'antd';
import type { CascaderProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => {
return {
root: {
borderRadius: token.borderRadiusLG,
},
};
});
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'meet-student',
label: 'meet-student',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const stylesObject: CascaderProps['styles'] = {
prefix: {
color: '#ccc',
},
suffix: {
color: '#ccc',
},
};
const stylesFn: CascaderProps['styles'] = (info): GetProp => {
if (info.props.variant === 'filled') {
return {
prefix: {
color: '#1890ff',
},
suffix: {
color: '#1890ff',
},
popup: {
listItem: {
color: '#1890ff',
},
},
};
}
return {};
};
const onChange: CascaderProps['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
return (
);
};
export default App;
```
### = 5.10.0">Panel
Used for inline view case.
```tsx
import React, { useState } from 'react';
import type { CascaderProps } from 'antd';
import { Cascader, Flex, Switch } from 'antd';
interface Option {
value: string | number;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const onMultipleChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => {
const [disabled, setDisabled] = useState(false);
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
```jsx
```
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| allowClear | Show clear button | boolean \| { clearIcon?: ReactNode } | true | 5.8.0: Support object type | `clearIcon`: 6.4.0 |
| ~~autoClearSearchValue~~ | Whether the current search will be cleared on selecting an item. Only applies when `multiple` is `true` | boolean | true | 5.9.0 | × |
| ~~bordered~~ | Whether has border style, please use `variant` instead | boolean | true | - | × |
| changeOnSelect | Change value on each selection if set to true, see above demo for details | boolean | false | | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.25.0 |
| defaultOpen | Initial visible of cascader popup | boolean | - | | × |
| defaultValue | Initial selected value | string\[] \| number\[] | \[] | | × |
| disabled | Whether disabled select | boolean | false | | × |
| displayRender | The render function of displaying selected options | (label, selectedOptions) => ReactNode | label => label.join(`/`) | `multiple`: 4.18.0 | × |
| tagRender | Custom render function for tags in `multiple` mode | (label: string, onClose: function, value: string) => ReactNode | - | | × |
| ~~popupClassName~~ | The additional className of popup overlay, use `classNames.popup.root` instead | string | - | 4.23.0 | × |
| ~~dropdownClassName~~ | The additional className of popup overlay, please use `classNames.popup.root` instead | string | - | - | × |
| ~~dropdownRender~~ | Customize dropdown content, use `popupRender` instead | (menus: ReactNode) => ReactNode | - | 4.4.0 | × |
| popupRender | Customize dropdown content | (menus: ReactNode) => ReactNode | - | | × |
| ~~dropdownStyle~~ | The style of dropdown menu, use `styles.popup.root` instead | CSSProperties | - | | × |
| expandIcon | Customize the current item expand icon | ReactNode | - | 4.4.0 | 6.3.0 |
| expandTrigger | expand current item when click or hover, one of `click` `hover` | string | `click` | | × |
| fieldNames | Custom field name for label and value and children | object | { label: `label`, value: `value`, children: `children` } | | × |
| getPopupContainer | Parent Node which the selector should be rendered to. Default to `body`. When position issues happen, try to modify it into scrollable content and position it relative. [example](https://codepen.io/afc163/pen/zEjNOy?editors=0010) | function(triggerNode) | () => document.body | | × |
| loadData | To load option lazily, and it cannot work with `showSearch` | (selectedOptions) => void | - | | × |
| loadingIcon | Customize the loading icon | ReactNode | - | | 6.3.0 |
| maxTagCount | Max tag count to show. `responsive` will cost render performance | number \| `responsive` | - | 4.17.0 | × |
| maxTagPlaceholder | Placeholder for not showing tags | ReactNode \| function(omittedValues) | - | 4.17.0 | × |
| maxTagTextLength | Max tag text length to show | number | - | 4.17.0 | × |
| notFoundContent | Specify content to show when no result matches | ReactNode | `Not Found` | | × |
| open | Set visible of cascader popup | boolean | - | 4.17.0 | × |
| options | The data options of cascade | [Option](#option)\[] | - | | × |
| placeholder | The input placeholder | string | - | | × |
| placement | Use preset popup align config from builtinPlacements | `bottomLeft` `bottomRight` `topLeft` `topRight` | `bottomLeft` | 4.17.0 | × |
| prefix | The custom prefix | ReactNode | - | 5.22.0 | × |
| ~~showArrow~~ | Whether to show the arrow icon, please use `suffixIcon={null}` instead | boolean | true | - | × |
| showSearch | Whether show search input in single mode | boolean \| [Object](#showsearch) | false | | `searchIcon`: 6.4.0 |
| size | The input size | `large` \| `medium` \| `small` | `medium` | | × |
| status | Set validation status | 'error' \| 'warning' | - | 4.19.0 | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.25.0 |
| suffixIcon | The custom suffix icon | ReactNode | - | | 6.4.0 |
| value | The selected value | string\[] \| number\[] | - | | × |
| variant | Variants of selector | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 \| `underlined`: 5.24.0 | 5.19.0 |
| onChange | Callback when finishing cascader select | (value, selectedOptions) => void | - | | × |
| onClear | Called when clear | () => void | - | - | × |
| ~~onDropdownVisibleChange~~ | Callback when popup shown or hidden, use `onOpenChange` instead | (value) => void | - | 4.17.0 | × |
| onOpenChange | Callback when popup shown or hidden | (value) => void | - | | × |
| ~~onPopupVisibleChange~~ | Callback when popup shown or hidden, please use `onOpenChange` instead | (value) => void | - | - | × |
| multiple | Support multiple or not | boolean | - | 4.17.0 | × |
| removeIcon | The custom remove icon | ReactNode | - | | 6.4.0 |
| showCheckedStrategy | The way to show selected items in the box (only effective when `multiple` is `true`). `Cascader.SHOW_CHILD`: just show child treeNode. `Cascader.SHOW_PARENT`: just show parent treeNode (when all child treeNode under the parent treeNode are checked) | `Cascader.SHOW_PARENT` \| `Cascader.SHOW_CHILD` | `Cascader.SHOW_PARENT` | 4.20.0 | × |
| ~~searchValue~~ | Set search value, Need work with `showSearch` | string | - | 4.17.0 | × |
| ~~onSearch~~ | The callback function triggered when input changed | (search: string) => void | - | 4.17.0 | × |
| ~~dropdownMenuColumnStyle~~ | The style of the drop-down menu column, use `styles.popup.listItem` instead | CSSProperties | - | | × |
| ~~popupMenuColumnStyle~~ | The style of the drop-down menu column, use `styles.popup.listItem` instead | CSSProperties | - | | × |
| optionRender | Customize the rendering dropdown options | (option: Option) => React.ReactNode | - | 5.16.0 | × |
### showSearch
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| autoClearSearchValue | Whether the current search will be cleared on selecting an item. Only applies when `multiple` is `true` | boolean | true | 5.9.0 |
| filter | The function will receive two arguments, inputValue and option, if the function returns true, the option will be included in the filtered set; Otherwise, it will be excluded | function(inputValue, path): boolean | - | |
| limit | Set the count of filtered items | number \| false | 50 | |
| matchInputWidth | Whether the width of list matches input, ([how it looks](https://github.com/ant-design/ant-design/issues/25779)) | boolean | true | |
| render | Used to render filtered options | function(inputValue, path): ReactNode | - | |
| sort | Used to sort filtered options | function(a, b, inputValue) | - | |
| searchValue | Set search value, Need work with `showSearch` | string | - | 4.17.0 |
| onSearch | The callback function triggered when input changed | (search: string) => void | - | 4.17.0 |
| searchIcon | Customize the search icon | ReactNode | - | 6.3.0 |
### Option
```typescript
interface Option {
value: string | number;
label?: React.ReactNode;
disabled?: boolean;
children?: Option[];
// Determines if this is a leaf node(effective when `loadData` is specified).
// `false` will force trade TreeNode as a parent node.
// Show expand icon even if the current node has no children.
isLeaf?: boolean;
}
```
## Methods
| Name | Description | Version |
| ------- | ------------ | ------- |
| blur() | Remove focus | |
| focus() | Get focus | |
## Semantic DOM
https://ant.design/components/cascader/semantic.md
## Design Token
## Component Token (Cascader)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| controlItemWidth | Width of item | string \| number | 111 |
| controlWidth | Width of Cascader | string \| number | 184 |
| dropdownHeight | Height of dropdown | string \| number | 180 |
| menuPadding | Padding of menu item (single column) | Padding \| undefined | 4 |
| optionPadding | Padding of menu item | Padding \| undefined | 5px 12px |
| optionSelectedBg | Background color of selected item | string | #e6f4ff |
| optionSelectedColor | Text color when option is selected | string | rgba(0,0,0,0.88) |
| optionSelectedFontWeight | Font weight of selected item | FontWeight \| undefined | 600 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| colorBgContainer | Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. | string | |
| colorBgContainerDisabled | Control the background color of container in disabled state. | string | |
| colorBorder | Default border color, used to separate different elements, such as: form separator, card separator, etc. | string | |
| colorHighlight | Control the color of page element when highlighted. | string | |
| colorIcon | Weak action. Such as `allowClear` or Alert close button | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorPrimaryHover | Hover state under the main color gradient. | string | |
| colorSplit | Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDisabled | Control the color of text in disabled state. | string | |
| colorWhite | Pure white color don't changed by theme | string | |
| controlInteractiveSize | Control the interactive size of control component. | number | |
| controlItemBgHover | Control the background color of control component item when hovering. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeIcon | Control the font size of operation icon in Select, Cascader, etc. Normally same as fontSizeSM. | number | |
| fontSizeLG | Large font size | number | |
| lineHeight | Line height of text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| lineWidthBold | The default line width of the outline class components, such as Button, Input, Select, etc. | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| motionDurationFast | Motion speed, fast speed. Used for small element animation interaction. | string | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseInBack | Preset motion curve. | string | |
| motionEaseOutBack | Preset motion curve. | string | |
| paddingXS | Control the extra small padding of the element. | number | |
| paddingXXS | Control the extra extra small padding of the element. | number | |
---
## changelog
Source: https://ant.design/components/changelog.md
---
order: 6
title: Changelog
timeline: true
tag: vVERSION
---
`antd` follows [Semantic Versioning 2.0.0](http://semver.org/).
#### Release Schedule
- Weekly release: patch version at the end of every week for routine bugfixes (anytime for an urgent bugfix).
- Monthly release: minor version at the end of every month for new features.
- Major version release is not included in this schedule for breaking changes and new features.
---
## 6.4.5
`2026-06-22`
- 🐞 Fix Dropdown vertical menu overflowing the viewport when the trigger is centered, keeping all menu items reachable. [#58214](https://github.com/ant-design/ant-design/pull/58214) [@18062706139fcz](https://github.com/18062706139fcz)
- 🐞 Fix Alert `actions` spacing not taking effect when hashed styles are enabled. [#58314](https://github.com/ant-design/ant-design/pull/58314) [@QDyanbing](https://github.com/QDyanbing)
- ⌨️ Fix Table not applying `aria-*` attributes to fixed header tables when `scroll` creates multiple tables. [#58339](https://github.com/ant-design/ant-design/pull/58339) [@biubiukam](https://github.com/biubiukam)
- 💄 Fix Pagination quick jumper input not following ConfigProvider `variant` styles. [#58371](https://github.com/ant-design/ant-design/pull/58371) [@biubiukam](https://github.com/biubiukam)
- 🌐 Localization
- 🇳🇴 Fill missing nb_NO (Norwegian) locale keys. [#58439](https://github.com/ant-design/ant-design/pull/58439) [@arvindfroi](https://github.com/arvindfroi)
## 6.4.4
`2026-06-12`
- 🛠 Fix build failures in Vite, Yarn PnP, Node 25 and other strict ESM environments caused by deep path imports of rc-component packages. [#58115](https://github.com/ant-design/ant-design/issues/58115) [@li-jia-nan](https://github.com/li-jia-nan) [@QDyanbing](https://github.com/QDyanbing)
- 🛠 Fix multiple components rendering empty wrapper DOM nodes when ReactNode content is an empty string. [#58160](https://github.com/ant-design/ant-design/pull/58160) [@QDyanbing](https://github.com/QDyanbing)
- Descriptions
- 🐞 Fix Descriptions width being unexpectedly inflated when nested inside a Table. [#58203](https://github.com/ant-design/ant-design/pull/58203) [@18062706139fcz](https://github.com/18062706139fcz)
- 🐞 Fix Descriptions responsive `column` value not behaving as expected. [#58058](https://github.com/ant-design/ant-design/pull/58058) [@kfylaktopoulos](https://github.com/kfylaktopoulos)
- Radio
- 🐞 Fix Radio.Group button style border radius and adjacent border display issue in vertical layout. [#58317](https://github.com/ant-design/ant-design/pull/58317) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Radio checked state not updating on click in uncontrolled mode. [#57917](https://github.com/ant-design/ant-design/pull/57917) [@QDyanbing](https://github.com/QDyanbing)
- Table
- 🐞 Fix Table incorrect semantic DOM structure in `virtual` mode. [#58134](https://github.com/ant-design/ant-design/pull/58134) [@meet-student](https://github.com/meet-student)
- ⌨️ Improve Table filter dropdown accessibility by marking the wrapper container as presentational. [#58164](https://github.com/ant-design/ant-design/pull/58164) [@ug-hero](https://github.com/ug-hero)
- Tour
- ⌨️ Fix Tour previous button text color readability on hover in primary type. [#58311](https://github.com/ant-design/ant-design/pull/58311) [@QDyanbing](https://github.com/QDyanbing)
- 🇰🇭 Add missing Tour Khmer km_KH locale text. [#58140](https://github.com/ant-design/ant-design/pull/58140) [@yogeshwaran-c](https://github.com/yogeshwaran-c)
- Transfer
- ⌨️ Fix Transfer not forwarding root HTML attributes which affects accessibility. [#58166](https://github.com/ant-design/ant-design/pull/58166) [@ZQDesigned](https://github.com/ZQDesigned)
- ⚡️ Improve Transfer iteration performance when collecting enabled item keys. [#58168](https://github.com/ant-design/ant-design/pull/58168) [@ug-hero](https://github.com/ug-hero)
- 🐞 Fix Menu icon animation jumping when collapsed. [#58271](https://github.com/ant-design/ant-design/pull/58271) [@murisans](https://github.com/murisans)
- 🐞 Fix Modal footer buttons vertical misalignment when `confirmLoading` is `true`. [#58120](https://github.com/ant-design/ant-design/pull/58120) [@xxiaoxiong](https://github.com/xxiaoxiong)
- 🐞 Fix Notification close button overlapping description content when title is not provided. [#58096](https://github.com/ant-design/ant-design/pull/58096) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Popover and Popconfirm not rendering when `title` or `content` is the number `0`. [#58296](https://github.com/ant-design/ant-design/pull/58296) [@afc163](https://github.com/afc163)
- 🐞 Fix Slider surrounding text being unexpectedly selected when dragging the handle in Safari. [#58024](https://github.com/ant-design/ant-design/pull/58024) [@yogeshwaran-c](https://github.com/yogeshwaran-c)
- 🐞 Fix Tabs more dropdown animation direction when popup placement flips upward. [#58202](https://github.com/ant-design/ant-design/pull/58202) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Tree.DirectoryTree `defaultExpandParent` not working. [#58068](https://github.com/ant-design/ant-design/pull/58068) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 Fix Upload progress bar becoming abnormally thick when `progress` is not configured. [#58126](https://github.com/ant-design/ant-design/pull/58126) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Icon spin animation stopping when multiple `iconPrefixCls` coexist. [#58253](https://github.com/ant-design/ant-design/pull/58253) [@18062706139fcz](https://github.com/18062706139fcz)
- 💄 Fix AutoComplete disabled custom input background color being darker than other disabled controls. [#58114](https://github.com/ant-design/ant-design/pull/58114) [@QDyanbing](https://github.com/QDyanbing)
- 💄 Fix Checkbox hover style remaining after tap on mobile devices. [#58085](https://github.com/ant-design/ant-design/pull/58085) [@unknowntocka](https://github.com/unknowntocka)
- 💄 Fix Empty SVG colors not using design tokens to support dark mode. [#58152](https://github.com/ant-design/ant-design/pull/58152) [@wanpan11](https://github.com/wanpan11)
- 💄 Fix Result and Popconfirm icon colors being overridden by global icon reset styles. [#58157](https://github.com/ant-design/ant-design/pull/58157) [@QDyanbing](https://github.com/QDyanbing)
- 💄 Fix Select selected option active state background color not following theme color. [#58069](https://github.com/ant-design/ant-design/pull/58069) [@QDyanbing](https://github.com/QDyanbing)
- 💄 Fix Tooltip and Popover arrow shadow being darker than container. [#57988](https://github.com/ant-design/ant-design/pull/57988) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 💄 Deepen `boxShadowTertiary` for better visibility on light backgrounds, affecting Card, Tour and Segmented. [#58205](https://github.com/ant-design/ant-design/pull/58205) [@afc163](https://github.com/afc163)
- ⌨️ Improve ColorPicker clear button semantic attributes for better accessibility. [#58040](https://github.com/ant-design/ant-design/pull/58040) [@ug-hero](https://github.com/ug-hero)
- ⌨️ Improve DatePicker and TimePicker clear button accessibility. [#58132](https://github.com/ant-design/ant-design/pull/58132) [@Pareder](https://github.com/Pareder)
- ⌨️ Improve Splitter split bar semantic attributes for better accessibility. [#58060](https://github.com/ant-design/ant-design/pull/58060) [@ug-hero](https://github.com/ug-hero)
- ⌨️ Improve Tag.CheckableTag semantic attributes for better accessibility. [#58067](https://github.com/ant-design/ant-design/pull/58067) [@ug-hero](https://github.com/ug-hero)
- 🛠 Fix Dropdown triggering React 19 element.ref deprecation warning when the trigger node has a ref. [#58056](https://github.com/ant-design/ant-design/pull/58056) [@QDyanbing](https://github.com/QDyanbing)
- 🛠 Fix multiple components rendering empty wrapper DOM nodes when ReactNode content is false. [#58088](https://github.com/ant-design/ant-design/pull/58088) [@QDyanbing](https://github.com/QDyanbing)
- 🌐 Localization
- 🇬🇧 Improve QRCode and ColorPicker British English en_GB locale to align with American English en_US. [#58224](https://github.com/ant-design/ant-design/pull/58224) [@JordanWeatherby](https://github.com/JordanWeatherby)
- 🇧🇷 Add missing Brazilian Portuguese pt_BR locale text for QRCode and ColorPicker. [#58188](https://github.com/ant-design/ant-design/pull/58188) [@yogeshwaran-c](https://github.com/yogeshwaran-c)
- TypeScript
- 🤖 Fix AutoComplete `showSearch` type leaking unsupported Select props. [#58104](https://github.com/ant-design/ant-design/pull/58104) [@sri443](https://github.com/sri443)
- 🤖 Improve Descriptions type definition to support native HTML attributes. [#58190](https://github.com/ant-design/ant-design/pull/58190) [@yogeshwaran-c](https://github.com/yogeshwaran-c)
## 6.4.3
`2026-05-18`
- 🐞 Fix DatePicker RangePicker empty placeholder when locale only defines singular `*Placeholder` fields. [#58020](https://github.com/ant-design/ant-design/pull/58020) [@yogeshwaran-c](https://github.com/yogeshwaran-c)
- 🐞 Fix Result rendering an empty `title` element when the `title` prop is not provided. [#58028](https://github.com/ant-design/ant-design/pull/58028) [@yogeshwaran-c](https://github.com/yogeshwaran-c)
- 🐞 Fix Select search input font size and line-height rendering issue in Safari. [#57990](https://github.com/ant-design/ant-design/pull/57990) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix strict ESM build errors caused by deep `@rc-component/util` runtime imports in Form, Input, Button and other components. [#57993](https://github.com/ant-design/ant-design/pull/57993) [@li-jia-nan](https://github.com/li-jia-nan)
- 🐞 Fix Transfer `filteredItems` not updating when `filterOption` or `direction` changes. [#58004](https://github.com/ant-design/ant-design/pull/58004) [@afc163](https://github.com/afc163)
- ⚡️ Improve Table and Mentions performance by reducing redundant array iterations. [#58006](https://github.com/ant-design/ant-design/pull/58006) [@ug-hero](https://github.com/ug-hero)
- Table
- 🛠 Rename Table filter types `FilterRestProps` to `FilterResetProps`, with a deprecated alias kept for compatibility. [#57985](https://github.com/ant-design/ant-design/pull/57985) [@ZQDesigned](https://github.com/ZQDesigned)
- ⚡️ Improve Table row selection performance by using Set-based lookup instead of O(n*m) `.includes()` checks. [#58004](https://github.com/ant-design/ant-design/pull/58004) [@afc163](https://github.com/afc163)
## 6.4.2
`2026-05-14`
- 🐞 Fix message and notification build error in strict ESM toolchains caused by deep rc notification runtime import. [#57976](https://github.com/ant-design/ant-design/pull/57976) [@QDyanbing](https://github.com/QDyanbing)
## 6.4.1
`2026-05-14`
- 🐞 Revert the `exports` field added in [#57930](https://github.com/ant-design/ant-design/pull/57930) to fix antd TypeScript type resolution failure under `moduleResolution: "bundler"`. [#57968](https://github.com/ant-design/ant-design/pull/57968) [@afc163](https://github.com/afc163)
- 🐞 Fix BorderBeam beam animation breaking at rounded corners. [#57969](https://github.com/ant-design/ant-design/pull/57969) [@QDyanbing](https://github.com/QDyanbing)
## 6.4.0
`2026-05-14`
- 🔥 Add BorderBeam component for animated border beam effect along container edges. [#57720](https://github.com/ant-design/ant-design/pull/57720) [@QDyanbing](https://github.com/QDyanbing)
- ConfigProvider
- 🆕 Add Select `allowClear` config support. [#56476](https://github.com/ant-design/ant-design/pull/56476) [@ug-hero](https://github.com/ug-hero)
- 🆕 Add Select `showSearch`, `allowClear`, `clearIcon`, `loadingIcon`, `menuItemSelectedIcon`, `removeIcon`, `suffixIcon` config support. [#56930](https://github.com/ant-design/ant-design/pull/56930) [@Pareder](https://github.com/Pareder)
- 🆕 Add DatePicker and TimePicker `allowClear` and `clearIcon` config support. [#57002](https://github.com/ant-design/ant-design/pull/57002) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Add RangePicker `allowClear`, `clearIcon`, `suffixIcon` config support. [#57075](https://github.com/ant-design/ant-design/pull/57075) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Add Modal `infoIcon`, `successIcon`, `warningIcon`, `errorIcon` config support. [#57168](https://github.com/ant-design/ant-design/pull/57168) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Add Upload `progress` config support. [#57283](https://github.com/ant-design/ant-design/pull/57283) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Add Upload `accept` config support. [#57286](https://github.com/ant-design/ant-design/pull/57286) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Add Modal and Drawer `focusable` config to control whether the component can receive focus. [#57314](https://github.com/ant-design/ant-design/pull/57314) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 Add Mentions `allowClear` config support. [#57330](https://github.com/ant-design/ant-design/pull/57330) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 Fix ConfigProvider css var prefix not following `prefixCls`. [#57803](https://github.com/ant-design/ant-design/pull/57803) [@QDyanbing](https://github.com/QDyanbing)
- Input
- 🆕 Add Input `allowClear.disabled` prop to disable the clear button while keeping it visible. [#57240](https://github.com/ant-design/ant-design/pull/57240) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Add Input.TextArea `allowClear.disabled` prop to disable the clear button while keeping it visible. [#57328](https://github.com/ant-design/ant-design/pull/57328) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Add Input `clear` semantic segment for customizing clear button `classNames` and `styles`. [#57391](https://github.com/ant-design/ant-design/pull/57391) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 Add Input.Search `searchIcon` prop to customize the search icon. [#57256](https://github.com/ant-design/ant-design/pull/57256) [@guoyunhe](https://github.com/guoyunhe)
- ⌨️ Improve Input.Password accessibility and add ConfigProvider support. [#57271](https://github.com/ant-design/ant-design/pull/57271) [@Pareder](https://github.com/Pareder)
- Splitter
- 🆕 Add Splitter `destroyOnHidden` prop for panel content mounting. [#56772](https://github.com/ant-design/ant-design/pull/56772) [@AhmeddEsmat](https://github.com/AhmeddEsmat)
- 🆕 Add Splitter smooth transition animation for collapsible panels. [#56814](https://github.com/ant-design/ant-design/pull/56814) [@spider-yamet](https://github.com/spider-yamet)
- 🗑 Deprecate Splitter `collapsibleIcon` and add `collapsible.icon` replacement. [#57044](https://github.com/ant-design/ant-design/pull/57044) [@wanpan11](https://github.com/wanpan11)
- 🐞 Fix unexpected 1px horizontal padding from Splitter.Panel. [#57838](https://github.com/ant-design/ant-design/pull/57838) [@wanpan11](https://github.com/wanpan11)
- Select
- 🐞 Fix Select option active style priority higher than selected. [#56924](https://github.com/ant-design/ant-design/pull/56924) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix Select `showArrowPaddingInlineEnd` not working for content gap. [#57769](https://github.com/ant-design/ant-design/pull/57769) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Select error status colors not matching Input across outlined and filled variants. [#57807](https://github.com/ant-design/ant-design/pull/57807) [@nickmopen](https://github.com/nickmopen)
- 🐞 Fix Select selected value font family not following antd token. [#57897](https://github.com/ant-design/ant-design/pull/57897) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Select and TreeSelect non-text `labelRender` content remaining visible while searching. [#57954](https://github.com/ant-design/ant-design/pull/57954) [@QDyanbing](https://github.com/QDyanbing)
- Image
- 🆕 Add Image `placeholder.progress` prop to show loading progress indicator. [#57173](https://github.com/ant-design/ant-design/pull/57173) [@afc163](https://github.com/afc163)
- 🆕 Add Image preview mask `closable` support. [#57611](https://github.com/ant-design/ant-design/pull/57611) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 Add Image `closeIcon` semantic node for `classNames` and `styles` configuration. [#57263](https://github.com/ant-design/ant-design/pull/57263) [@coding-ice](https://github.com/coding-ice)
- ⌨️ Add focus-visible styles and focusTrap support for Image preview. [#57610](https://github.com/ant-design/ant-design/pull/57610) [@aojunhao123](https://github.com/aojunhao123)
- Typography
- 🆕 Add Typography `actions` placement prop to control the position of action buttons. [#57440](https://github.com/ant-design/ant-design/pull/57440) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 Add Typography default styles for table elements. [#57633](https://github.com/ant-design/ant-design/pull/57633) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Add Typography more flexible semantic structure. [#56971](https://github.com/ant-design/ant-design/pull/56971) [@zombieJ](https://github.com/zombieJ)
- Theme
- 🆕 Add `colorErrorAffix` Design Token to control the error color of input affix. [#57604](https://github.com/ant-design/ant-design/pull/57604) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Add `colorWarningAffix` Design Token to control the warning color of input affix. [#57760](https://github.com/ant-design/ant-design/pull/57760) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 Fix Design Token heading font size tokens not supporting string values. [#57598](https://github.com/ant-design/ant-design/pull/57598) [@EndlessLucky](https://github.com/EndlessLucky)
- Wave
- 🆕 Add Wave `triggerType` config to control which element triggers the wave effect. [#57402](https://github.com/ant-design/ant-design/pull/57402) [@wanpan11](https://github.com/wanpan11)
- 🐞 Fix Wave ignoring transparent hex colors. [#57859](https://github.com/ant-design/ant-design/pull/57859) [@li-jia-nan](https://github.com/li-jia-nan)
- Tree
- 🆕 Add `itemSwitcher` semantic for Tree and TreeSelect. [#57281](https://github.com/ant-design/ant-design/pull/57281) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Tree scroll-to-top when context menu closes and tree regains focus. [#57329](https://github.com/ant-design/ant-design/pull/57329) [@aojunhao123](https://github.com/aojunhao123)
- Tag
- 🆕 Add Tag `close` semantic node for close icon `classNames` and `styles` configuration. [#57331](https://github.com/ant-design/ant-design/pull/57331) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 Add Tag CheckableTagGroup per-option `className` and `style` support. [#57840](https://github.com/ant-design/ant-design/pull/57840) [@ZQDesigned](https://github.com/ZQDesigned)
- Table
- 🆕 Add Table `column` prop to configure columns via ConfigProvider. [#57545](https://github.com/ant-design/ant-design/pull/57545) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 Add Table `scrollTo` align parameter and upgrade rc-table to 1.10.0. [#57594](https://github.com/ant-design/ant-design/pull/57594) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- Notification
- 🆕 Add Notification fully semantic structure support. [#57824](https://github.com/ant-design/ant-design/pull/57824) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix Notification close spacing without title. [#57821](https://github.com/ant-design/ant-design/pull/57821) [@QDyanbing](https://github.com/QDyanbing)
- Menu
- 🐞 Fix Menu item extra layout with icon. [#57818](https://github.com/ant-design/ant-design/pull/57818) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Menu item extra ellipsis and tooltip padding. [#57823](https://github.com/ant-design/ant-design/pull/57823) [@QDyanbing](https://github.com/QDyanbing)
- Form
- 🆕 Add Form `labelAlign` prop to ConfigProvider for global label alignment control. [#56979](https://github.com/ant-design/ant-design/pull/56979) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Add Form semantic DOM support for `help`, `helpItem` and `extra` to allow custom styling. [#57607](https://github.com/ant-design/ant-design/pull/57607) [@QDyanbing](https://github.com/QDyanbing)
- DatePicker
- 🆕 Add DatePicker `tagRender` prop to customize tag rendering in multiple mode. [#57706](https://github.com/ant-design/ant-design/pull/57706) [@QDyanbing](https://github.com/QDyanbing)
- ⌨️ Improve DatePicker and TimePicker accessibility. [#57400](https://github.com/ant-design/ant-design/pull/57400) [@cyphercodes](https://github.com/cyphercodes)
- Button
- 🆕 Add Button default colors for solid variants. [#57495](https://github.com/ant-design/ant-design/pull/57495) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Button icon glyph vertical centering in icon-only buttons. [#57896](https://github.com/ant-design/ant-design/pull/57896) [@RenzoMXD](https://github.com/RenzoMXD)
- 🆕 Add Alert `variant` prop to support filled and outlined styles, and ConfigProvider support. [#57764](https://github.com/ant-design/ant-design/pull/57764) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Add Anchor.Link `targetOffset` prop to set scroll offset for each link individually. [#57521](https://github.com/ant-design/ant-design/pull/57521) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Add App `ref` support to access instance methods programmatically. [#56951](https://github.com/ant-design/ant-design/pull/56951) [@li-jia-nan](https://github.com/li-jia-nan)
- 🆕 Add Badge `paddingInline` design token. [#57891](https://github.com/ant-design/ant-design/pull/57891) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Add Calendar `itemContent` semantic DOM support. [#57430](https://github.com/ant-design/ant-design/pull/57430) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Add Cascader and ConfigProvider `searchIcon`, `clearIcon`, `removeIcon`, `suffixIcon` config support. [#56725](https://github.com/ant-design/ant-design/pull/56725) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 Fix Checkbox redundant Form.Item native input size and width/height overlay settings. [#57714](https://github.com/ant-design/ant-design/pull/57714) [@lcsy1234](https://github.com/lcsy1234)
- 🐞 Fix Dropdown missing `forwardRef` for React 18 compatibility. [#57902](https://github.com/ant-design/ant-design/pull/57902) [@xxiaoxiong](https://github.com/xxiaoxiong)
- 🆕 Add FloatButton `disabled` support. [#57123](https://github.com/ant-design/ant-design/pull/57123) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix Mentions popup z-index. [#57873](https://github.com/ant-design/ant-design/pull/57873) [@meet-student](https://github.com/meet-student)
- 🆕 Add Modal `closeIcon` semantic node for `classNames` and `styles` configuration. [#57264](https://github.com/ant-design/ant-design/pull/57264) [@divyeshagrawal](https://github.com/divyeshagrawal)
- 🆕 Add Popconfirm `icon` semantic node for `classNames` and `styles` configuration. [#57528](https://github.com/ant-design/ant-design/pull/57528) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 Add Space.Addon design token support. [#56915](https://github.com/ant-design/ant-design/pull/56915) [@zombieJ](https://github.com/zombieJ)
- 🛎 Update Spin `size` prop deprecation warning and remove redundant check. [#57812](https://github.com/ant-design/ant-design/pull/57812) [@meet-student](https://github.com/meet-student)
- 🆕 Add Statistic value semantic `classNames` and `styles` support. [#57656](https://github.com/ant-design/ant-design/pull/57656) [@li-jia-nan](https://github.com/li-jia-nan)
- 🆕 Add Tabs `remove` semantic node for close button `classNames` and `styles` configuration. [#57267](https://github.com/ant-design/ant-design/pull/57267) [@coding-ice](https://github.com/coding-ice)
- 🆕 Add Tour `closeIcon` semantic node for `classNames` and `styles` configuration. [#57268](https://github.com/ant-design/ant-design/pull/57268) [@coding-ice](https://github.com/coding-ice)
- 🆕 Add Transfer source and target semantic DOM support. [#57101](https://github.com/ant-design/ant-design/pull/57101) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 Add Upload image type detection with avif, tif and tiff. [#57287](https://github.com/ant-design/ant-design/pull/57287) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 Fix Watermark not covering Table fixed columns by default. [#57813](https://github.com/ant-design/ant-design/pull/57813) [@QDyanbing](https://github.com/QDyanbing)
- 🇺🇸 Add Form `defaultValidateMessages` for 8 languages. [#57038](https://github.com/ant-design/ant-design/pull/57038) [@mixelburg](https://github.com/mixelburg) [#57045](https://github.com/ant-design/ant-design/pull/57045) [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent)
- 🆕 Add antd `GetProp` support for Return type. [#57001](https://github.com/ant-design/ant-design/pull/57001) [@crazyair](https://github.com/crazyair)
- 📖 Add Agent Readiness files (robots.txt, sitemap, agent-skills, api-catalog, etc.) to improve AI agent friendliness for ant.design. [#57903](https://github.com/ant-design/ant-design/pull/57903) [@afc163](https://github.com/afc163)
## 6.3.7
`2026-04-27`
- Input
- 🐞 Fix Input.OTP masked value being visible when selected on Windows. [#57689](https://github.com/ant-design/ant-design/pull/57689) [@QDyanbing](https://github.com/QDyanbing)
- ⌨️ Improve Input accessibility for the clear button. [#57432](https://github.com/ant-design/ant-design/pull/57432) [@cyphercodes](https://github.com/cyphercodes)
- 🐞 Fix Card rendering an empty body wrapper when no content was provided. [#57735](https://github.com/ant-design/ant-design/pull/57735) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix InputNumber selection highlight radius. [#57705](https://github.com/ant-design/ant-design/pull/57705) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Tooltip semantic configs such as `className`, `styles`, etc. leaking into Popover and Popconfirm from ConfigProvider. [#57731](https://github.com/ant-design/ant-design/pull/57731) [@pikanohup](https://github.com/pikanohup)
- 🐞 Fix Typography.Link cannot trigger action buttons such as copy, edit, etc. when disabled. [#57762](https://github.com/ant-design/ant-design/pull/57762) [@aviu16](https://github.com/aviu16)
- 🐞 Fix ConfigProvider language packs export from ESM/CJS dist files. [#57318](https://github.com/ant-design/ant-design/pull/57318) [@ug-hero](https://github.com/ug-hero)
- 💄 Fix Alert focus styles for the close button. [#57695](https://github.com/ant-design/ant-design/pull/57695) [@KittyGiraudel](https://github.com/KittyGiraudel)
## 6.3.6
`2026-04-17`
- 🐞 Fix InputNumber disabled handlers showing hover styles. [#57592](https://github.com/ant-design/ant-design/pull/57592) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Space.Addon wrapping CJK content in compact layouts. [#57622](https://github.com/ant-design/ant-design/pull/57622) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Cascader menu item ellipsis styles for long option labels. [#57540](https://github.com/ant-design/ant-design/pull/57540) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Image preview focus not being locked when opened via keyboard, and restore focus to trigger element after preview closes. [#57613](https://github.com/ant-design/ant-design/pull/57613) [#57614](https://github.com/ant-design/ant-design/pull/57614) [@aojunhao123](https://github.com/aojunhao123)
- 🐞 Fix Input disabled border color to use `colorBorderDisabled` token. [#57518](https://github.com/ant-design/ant-design/pull/57518) [@Gdhanush-13](https://github.com/Gdhanush-13)
- 🐞 MISC: Fix some expand animation crash issues. [#57636](https://github.com/ant-design/ant-design/pull/57636) [@momesana](https://github.com/momesana)
- 🐞 Fix Notification close button overlapping description when title is empty. [#57590](https://github.com/ant-design/ant-design/pull/57590) [@EndlessLucky](https://github.com/EndlessLucky)
- 🐞 Fix Radio hover color display issue in disabled state. [#57562](https://github.com/ant-design/ant-design/pull/57562) [@yfy3939](https://github.com/yfy3939)
- Table
- ⚡️ Improve Table filter performance by caching flattened filter keys. [#57546](https://github.com/ant-design/ant-design/pull/57546) [@Jiyur](https://github.com/Jiyur)
- ⚡️ Improve Table filter search performance by reusing normalized search input. [#57651](https://github.com/ant-design/ant-design/pull/57651) [@li-jia-nan](https://github.com/li-jia-nan)
- 🐞 Fix Table `rowSelection` to use `selectionColumnWidth` from Design Token as default `columnWidth`. [#57621](https://github.com/ant-design/ant-design/pull/57621) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 Fix Design Token shadow tokens not adapting to dark theme. [#57511](https://github.com/ant-design/ant-design/pull/57511) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Transfer remove button still changing color on hover when the list item is disabled. [#57579](https://github.com/ant-design/ant-design/pull/57579) [@Jiyur](https://github.com/Jiyur)
- 🐞 Fix Tree checkbox, switcher and content alignment when parent nodes have multiple lines of content. [#57471](https://github.com/ant-design/ant-design/pull/57471) [@jiangrong-devops](https://github.com/jiangrong-devops)
## 6.3.5
`2026-03-30`
- 🐞 Fix Image preview action buttons not resetting native button styles. [#57491](https://github.com/ant-design/ant-design/pull/57491) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix TimePicker column cannot scroll directly on touch devices. [#57468](https://github.com/ant-design/ant-design/pull/57468) [@afc163](https://github.com/afc163)
- 🐞 MISC: Fix Icon not being centered in certain scenarios. [#57460](https://github.com/ant-design/ant-design/pull/57460) [@QDyanbing](https://github.com/QDyanbing)
## 6.3.4
`2026-03-24`
- 🔥 Add [`@ant-design/cli`](https://www.npmjs.com/package/@ant-design/cli) official command-line tool for querying Ant Design component knowledge, analyzing project usage, and guiding migrations offline. [#57413](https://github.com/ant-design/ant-design/pull/57413) [@afc163](https://github.com/afc163)
- 🐞 Fix Form.List losing sibling field values when using `onValuesChange`. [#57399](https://github.com/ant-design/ant-design/pull/57399) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix missing `screenXXXLMin` in `useToken` causing incorrect antd.css to be generated. [#57372](https://github.com/ant-design/ant-design/pull/57372) [@sealye09](https://github.com/sealye09)
- 🐞 Fix ConfigProvider component config typings to expose semantic `classNames` and `styles` for supported components. [#57396](https://github.com/ant-design/ant-design/pull/57396) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Image `fetchPriority` prop not being passed through to the ` ` element. [#57392](https://github.com/ant-design/ant-design/pull/57392) [@aojunhao123](https://github.com/aojunhao123)
- Menu
- 🐞 Fix Menu SubMenu parent item not applying custom hover color via ConfigProvider. [#57374](https://github.com/ant-design/ant-design/pull/57374) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 Fix Menu collapsed icons appearing misaligned when customizing `collapsedIconSize`. [#57360](https://github.com/ant-design/ant-design/pull/57360) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Table controlled popover in column title being rendered twice when scroll is enabled. [#57342](https://github.com/ant-design/ant-design/pull/57342) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Transfer `render` prop returning JSX elements causing search to fail. [#57133](https://github.com/ant-design/ant-design/pull/57133) [@WustLCQ](https://github.com/WustLCQ)
- 🐞 Fix Tree custom `switcherIcon` missing `switcher-line-icon` className when `showLine` is enabled. [#57303](https://github.com/ant-design/ant-design/pull/57303) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Watermark TypeScript errors when `onRemove` is omitted. [#57344](https://github.com/ant-design/ant-design/pull/57344) [@QDyanbing](https://github.com/QDyanbing)
## 6.3.3
`2026-03-16`
- Image
- 💄 Improve Image preview mask blur transition for `backdrop-filter` to reduce flicker perception. [#57299](https://github.com/ant-design/ant-design/pull/57299) [@mango766](https://github.com/mango766)
- 🐞 Fix Image showing move cursor when `movable={false}`. [#57288](https://github.com/ant-design/ant-design/pull/57288) [@ug-hero](https://github.com/ug-hero)
- ⌨️ Improve App link `:focus-visible` outline to enhance keyboard accessibility. [#57266](https://github.com/ant-design/ant-design/pull/57266) [@ug-hero](https://github.com/ug-hero)
- 🐞 Fix Form required mark using hardcoded `SimSun` font. [#57273](https://github.com/ant-design/ant-design/pull/57273) [@mavericusdev](https://github.com/mavericusdev)
- 🐞 Fix Grid media size mapping issue for `xxxl` breakpoint. [#57246](https://github.com/ant-design/ant-design/pull/57246) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 Fix Tree scrolling to top when clicking node. [#57242](https://github.com/ant-design/ant-design/pull/57242) [@aojunhao123](https://github.com/aojunhao123)
## 6.3.2
`2026-03-09`
- 🐞 Fix Form.Item validation failure caused by a timing issue when using dynamic `rules` and `dependencies` together. [#57147](https://github.com/ant-design/ant-design/pull/57147) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix InputNumber height in `borderless` variant when using with Input or Select. [#57162](https://github.com/ant-design/ant-design/pull/57162) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Radio.Group radio button width when options text has different length or breaks. [#57171](https://github.com/ant-design/ant-design/pull/57171) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Skeleton.Avatar, Skeleton.Button, Skeleton.Input, Rate and Spin cannot take effect when `componentSize` is set globally. [#57093](https://github.com/ant-design/ant-design/pull/57093) [#57106](https://github.com/ant-design/ant-design/pull/57106) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Splitter may calculate wrong `size` if some panel in controlled mode. [#57142](https://github.com/ant-design/ant-design/pull/57142) [@js0753](https://github.com/js0753)
- 🐞 Fix Tree and TreeSelect line alignment problem when customizing `titleHeight` property. [#56785](https://github.com/ant-design/ant-design/pull/56785) [@QDyanbing](https://github.com/QDyanbing)
- 💄 Fix Checkbox.Group checkbox width when options text has different length or breaks. [#57144](https://github.com/ant-design/ant-design/pull/57144) [@QDyanbing](https://github.com/QDyanbing)
- 💄 Fix ConfigProvider `csp` not taking effect on all the dynamic style. [#57159](https://github.com/ant-design/ant-design/pull/57159) [@zombieJ](https://github.com/zombieJ)
- Select
- 💄 Fix Select text jumping problem in Firefox browser. [#57030](https://github.com/ant-design/ant-design/pull/57030) [@pierreeurope](https://github.com/pierreeurope)
- 💄 Fix Select cannot set `visibility: hidden` via `style` property. [#56720](https://github.com/ant-design/ant-design/pull/56720) [@claytonlin1110](https://github.com/claytonlin1110)
- Upload
- 💄 Fix Upload has invalid blank area in `picture-card` mode with empty data. [#57157](https://github.com/ant-design/ant-design/pull/57157) [@QDyanbing](https://github.com/QDyanbing)
- ⌨️ Improve Upload to always show item action area on non-hover or coarse-pointer devices. [#57156](https://github.com/ant-design/ant-design/pull/57156) [@Arktomson](https://github.com/Arktomson)
- 🌐 Add `es_US` locale preset. [#57137](https://github.com/ant-design/ant-design/pull/57137) [@yuriidumych-max](https://github.com/yuriidumych-max)
- 🛠 Unify `size` enumeration, replace `default` with `medium` for Badge, Card, Progress, Steps, Switch and Spin, replace `middle` and `default` with `medium` and `large` for Descriptions, replace `middle` with `medium` for Table and Divider. [#57127](https://github.com/ant-design/ant-design/pull/57127) [#57106](https://github.com/ant-design/ant-design/pull/57106) [@QDyanbing](https://github.com/QDyanbing)
- 🛠 Unify `size` className for all components DOM. [#57106](https://github.com/ant-design/ant-design/pull/57106) [@QDyanbing](https://github.com/QDyanbing)
- TypeScript
- 🤖 Add Upload.Dragger generic type definition support. [#57103](https://github.com/ant-design/ant-design/pull/57103) [@fnoopv](https://github.com/fnoopv)
- 🤖 Fix Modal `KeyboardEvent` type definition for the arguments of `onCancel` event handler. [#57048](https://github.com/ant-design/ant-design/pull/57048) [@eureka928](https://github.com/eureka928)
## 6.3.1
`2026-02-24`
- Select
- 🐞 Fix Select incorrect dropdown height when `value` is an empty string. [#56976](https://github.com/ant-design/ant-design/pull/56976) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix Select value echo issue when `value` is an empty string. [#56966](https://github.com/ant-design/ant-design/pull/56966) [@luozz1994](https://github.com/luozz1994)
- 🐞 Fix Select & TreeSelect selected value text still visible when searching. [#56946](https://github.com/ant-design/ant-design/pull/56946)
- 🐞 Fix TreeSelect Checkbox being compressed when multi-line text is present. [#56961](https://github.com/ant-design/ant-design/pull/56961) [@luozz1994](https://github.com/luozz1994)
- 🐞 Fix Typography hovering copy button triggering ellipsis tooltip when both `copyable` and `ellipsis` are enabled; fix ellipsis tooltip not appearing after moving back from copy button. [#56855](https://github.com/ant-design/ant-design/pull/56855) [@claytonlin1110](https://github.com/claytonlin1110)
- 🐞 Fix Progress animation overflow when `status="active"`. [#56972](https://github.com/ant-design/ant-design/pull/56972) [@aibayanyu20](https://github.com/aibayanyu20)
- 🐞 Fix Upload picture-wall mode list overflow and overlap when file count exceeds one row. [#56945](https://github.com/ant-design/ant-design/pull/56945) [@xbsheng](https://github.com/xbsheng)
- 🐞 Fix Image flickering in some browsers when opening preview. [#56937](https://github.com/ant-design/ant-design/pull/56937) [@zombieJ](https://github.com/zombieJ)
- ⌨️ ♿ Add `prefers-reduced-motion` media query support for Button, Checkbox, Radio, Switch, Segmented to disable transitions for improved accessibility. [#56902](https://github.com/ant-design/ant-design/pull/56902) [@li-jia-nan](https://github.com/li-jia-nan)
- 🐞 Fix Input height inconsistency with Select when using `variant="borderless"`. [#57014](https://github.com/ant-design/ant-design/pull/57014) [@njlazzar-su](https://github.com/njlazzar-su)
- 🐞 Fix Modal `confirm` method layout whitespace when `icon` is empty. [#57024](https://github.com/ant-design/ant-design/pull/57024) [@Arktomson](https://github.com/Arktomson)
- 🐞 Add `aria-disabled` attribute for disabled options in Select component.[#57049](https://github.com/ant-design/ant-design/pull/57049) [@meet-student](https://github.com/meet-student)
## 6.3.0
`2026-02-10`
- ConfigProvider
- 🆕 Support ConfigProvider global configuration of `maskClosable` for Modal and Drawer. [#56739](https://github.com/ant-design/ant-design/pull/56739) [@luozz1994](https://github.com/luozz1994)
- 🆕 Support ConfigProvider `suffixIcon` global configuration for DatePicker and TimePicker. [#56709](https://github.com/ant-design/ant-design/pull/56709) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Support ConfigProvider `expandIcon` and `loadingIcon` global configuration for Cascader. [#56482](https://github.com/ant-design/ant-design/pull/56482) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Support ConfigProvider `scroll` global configuration for Table. [#56628](https://github.com/ant-design/ant-design/pull/56628) [@Clayton](https://github.com/Clayton)
- 🆕 Support ConfigProvider `className` and `style` configuration for App, and `arrow` prop for ColorPicker. [#56573](https://github.com/ant-design/ant-design/pull/56573) [@zombieJ](https://github.com/zombieJ)
- 🆕 Support ConfigProvider `loadingIcon` global configuration for Button. [#56439](https://github.com/ant-design/ant-design/pull/56439) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Support ConfigProvider `rangePicker.separator` global configuration. [#56499](https://github.com/ant-design/ant-design/pull/56499) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Support ConfigProvider `tooltipIcon` and `tooltipProps` global configuration for Form. [#56372](https://github.com/ant-design/ant-design/pull/56372) [@guoyunhe](https://github.com/guoyunhe)
- Upload
- 🆕 Add Upload `classNames.trigger` and `styles.trigger` props. [#56578](https://github.com/ant-design/ant-design/pull/56578) [@QdabuliuQ](https://github.com/QdabuliuQ)
- 🆕 Support Upload.Dragger `onDoubleClick` event. [#56579](https://github.com/ant-design/ant-design/pull/56579) [@ug-hero](https://github.com/ug-hero)
- 🐞 Fix Upload missing default height for `picture-card` / `picture-circle` parent nodes. [#56864](https://github.com/ant-design/ant-design/pull/56864) [@wanpan11](https://github.com/wanpan11)
- 🆕 Add Grid `xxxl` (1920px) breakpoint to adapt to FHD screens. [#56825](https://github.com/ant-design/ant-design/pull/56825) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Support Switch `indicator` customization for semantic structure. [#56710](https://github.com/ant-design/ant-design/pull/56710) [@zombieJ](https://github.com/zombieJ)
- Button
- 🐞 Fix Button reversed `hover` and `active` colors for `color` in dark theme. [#56872](https://github.com/ant-design/ant-design/pull/56872) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix Button border size not following Design Token `lineWidth`. [#56683](https://github.com/ant-design/ant-design/pull/56683) [@zombieJ](https://github.com/zombieJ)
- Select
- 💄 Remove Select redundant `-content-value` div DOM in single mode to optimize semantic structure, allowing override via `classNames` and `styles`. [#56811](https://github.com/ant-design/ant-design/pull/56811) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix Select `notFoundContent` not taking effect. [#56756](https://github.com/ant-design/ant-design/pull/56756) [@QdabuliuQ](https://github.com/QdabuliuQ)
- Radio
- 🐞 Fix Radio.Group extra right margin for radio items when vertically aligned. [#56909](https://github.com/ant-design/ant-design/pull/56909) [@jany55555](https://github.com/jany55555)
- 💄 Remove Radio `-inner` DOM node of `icon` sub-element for better semantic structure adaptation. [#56783](https://github.com/ant-design/ant-design/pull/56783) [@zombieJ](https://github.com/zombieJ)
- 💄 Disable Modal & Drawer mask blur effect by default. [#56781](https://github.com/ant-design/ant-design/pull/56781) [@aojunhao123](https://github.com/aojunhao123)
- 🐞 Fix Tooltip & Popover popup animation starting position being shifted to the left. [#56887](https://github.com/ant-design/ant-design/pull/56887) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix List color-related tokens not working for deprecated component config. [#56913](https://github.com/ant-design/ant-design/pull/56913) [@zombieJ](https://github.com/zombieJ)
- 🛠 Refactor Spin DOM structure to align across different scenarios and support full Semantic Structure. [#56852](https://github.com/ant-design/ant-design/pull/56852) [@zombieJ](https://github.com/zombieJ)
- ⌨️ ♿ Add Icon accessibility names to the search icon SVG to improve screen reader support. [#56521](https://github.com/ant-design/ant-design/pull/56521) [@huangkevin-apr](https://github.com/huangkevin-apr)
- 🐞 Fix Cascader filter list resetting immediately when closing on selection in search mode, affecting UX. [#56764](https://github.com/ant-design/ant-design/pull/56764) [@zombieJ](https://github.com/zombieJ)
- ⌨️ ♿ Improve Tree accessibility support. [#56716](https://github.com/ant-design/ant-design/pull/56716) [@aojunhao123](https://github.com/aojunhao123)
- 🐞 Support ColorPicker semantic structure for selection block, and fix `root` semantic being incorrectly applied to popup elements. [#56607](https://github.com/ant-design/ant-design/pull/56607) [@zombieJ](https://github.com/zombieJ)
- 💄 Change Avatar default value of `size` from `default` to `medium` for consistency. [#56440](https://github.com/ant-design/ant-design/pull/56440) [@guoyunhe](https://github.com/guoyunhe)
- 💄 Remove Checkbox `-inner` DOM node of `icon` sub-element for better semantic structure adaptation. [#56783](https://github.com/ant-design/ant-design/pull/56783) [@zombieJ](https://github.com/zombieJ)
- MISC
- 🐞 MISC: Fix React Compiler compatibility in UMD version, now disabled by default. [#56830](https://github.com/ant-design/ant-design/pull/56830) [@zombieJ](https://github.com/zombieJ)
- 🛠 Streamline `styles` and `classNames` type definitions for better standardization. [#56758](https://github.com/ant-design/ant-design/pull/56758) [@crazyair](https://github.com/crazyair)
## 6.2.3
`2026-02-02`
- Button
- 🐞 Fix Button `defaultBg`, `defaultColor`, `defaultHoverColor` and `defaultActiveColor` tokens not taking effect. [#56238](https://github.com/ant-design/ant-design/pull/56238) [@ug-hero](https://github.com/ug-hero)
- 🐞 Fix Button default tokens not taking effect. [#56719](https://github.com/ant-design/ant-design/pull/56719) [@unknowntocka](https://github.com/unknowntocka)
- 🐞 Fix Button `variant="solid"` borders displaying incorrectly inside Space.Compact. [#56486](https://github.com/ant-design/ant-design/pull/56486) [@Pareder](https://github.com/Pareder)
- 🐞 Fix Input.TextArea ref missing `nativeElement` property. [#56803](https://github.com/ant-design/ant-design/pull/56803) [@smith3816](https://github.com/smith3816)
- 🐞 Fix Flex default `align` not taking effect when using `orientation`. [#55950](https://github.com/ant-design/ant-design/pull/55950) [@YingtaoMo](https://github.com/YingtaoMo)
- 🐞 Fix Typography link selector specificity being too low causing styles to be overridden. [#56759](https://github.com/ant-design/ant-design/pull/56759) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix ColorPicker HEX input allowing invalid characters. [#56752](https://github.com/ant-design/ant-design/pull/56752) [@treephesians](https://github.com/treephesians)
## 6.2.2
`2026-01-26`
- 🐞 Fix Button with href wrapped by Typography showing incorrect color and flickering outline on hover. [#56619](https://github.com/ant-design/ant-design/pull/56619) [@QdabuliuQ](https://github.com/QdabuliuQ)
- 🐞 Fix component token not taking effect for Button with `type="text"`. [#56291](https://github.com/ant-design/ant-design/pull/56291) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix where components within the Popover were affected by the state association with Form.Item. [#56728](https://github.com/ant-design/ant-design/pull/56728)
- 🐞 Fix the placeholders displayed incorrectly when selecting multiple items in Select. [#56675](https://github.com/ant-design/ant-design/pull/56675)
- 💄 Fix misaligned elements in Pagination when the global `fontSize` is increased. [#56715](https://github.com/ant-design/ant-design/pull/56715) [@QDyanbing](https://github.com/QDyanbing)
- 💄 Fix incorrect Drawer dragger position in RTL mode. [#56693](https://github.com/ant-design/ant-design/pull/56693) [@QdabuliuQ](https://github.com/QdabuliuQ)
## 6.2.1
`2026-01-20`
- 🐞 Fix Button child element's `className` be cleared if it contains two Chinese characters. [#56593](https://github.com/ant-design/ant-design/pull/56593) [@QdabuliuQ](https://github.com/QdabuliuQ)
- 🐞 Fix DatePicker DOM not updated bug after update `suffixIcon` as `null`. [#56637](https://github.com/ant-design/ant-design/pull/56637) [@AlanQtten](https://github.com/AlanQtten)
- 🐞 Fix Table content area border radius when set border radius for container. [#56478](https://github.com/ant-design/ant-design/pull/56478) [@QDyanbing](https://github.com/QDyanbing)
- 💄 Fix Card unexpected border radius for Body area. [#56653](https://github.com/ant-design/ant-design/pull/56653) [@ug-hero](https://github.com/ug-hero)
- 💄 MISC: Fix unexpected `undefined` and `null` in the injected styles. [#56636](https://github.com/ant-design/ant-design/pull/56636) [@li-jia-nan](https://github.com/li-jia-nan)
- 💄 MISC: Improve `background` transition to `background-color` for all components. [#56598](https://github.com/ant-design/ant-design/pull/56598) [@li-jia-nan](https://github.com/li-jia-nan)
- 🛠 Improve Grid use `genCssVar` method to generate more stable CSS variable names. [#56635](https://github.com/ant-design/ant-design/pull/56635) [@li-jia-nan](https://github.com/li-jia-nan)
- 🛠 Improve @ant-design/icons usage to avoid depend on full package since externals. [#56639](https://github.com/ant-design/ant-design/pull/56639) [@ShenHongFei](https://github.com/ShenHongFei)
## 6.2.0
`2026-01-13`
- 🛠 Button, Masonry, Mentions, Select, Space, Splitter, Steps and other components batch use `genCssVar` method to generate more stable CSS variable names. [#56562](https://github.com/ant-design/ant-design/pull/56562) [#56559](https://github.com/ant-design/ant-design/pull/56559) [#56557](https://github.com/ant-design/ant-design/pull/56557) [#56555](https://github.com/ant-design/ant-design/pull/56555) [#56550](https://github.com/ant-design/ant-design/pull/56550) [#56547](https://github.com/ant-design/ant-design/pull/56547) [#56546](https://github.com/ant-design/ant-design/pull/56546) [#56529](https://github.com/ant-design/ant-design/pull/56529) [@li-jia-nan](https://github.com/li-jia-nan)
- 🆕 QRCode adds `marginSize` property for displaying QR code margin area. [#56569](https://github.com/ant-design/ant-design/pull/56569) [@afc163](https://github.com/afc163)
- 🆕 Tour adds `keyboard` property to configure keyboard operations. [#56581](https://github.com/ant-design/ant-design/pull/56581) [@cactuser-Lu](https://github.com/cactuser-Lu)
- Tooltip
- 🆕 Tooltip adds `maxWidth` design token. [#56540](https://github.com/ant-design/ant-design/pull/56540) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Tooltip/Popover/Popconfirm can be closed with ESC by default. [#56492](https://github.com/ant-design/ant-design/pull/56492) [@aojunhao123](https://github.com/aojunhao123)
- 🛠 Steps remove useless styles. [#56565](https://github.com/ant-design/ant-design/pull/56565) [@li-jia-nan](https://github.com/li-jia-nan)
- 🆕 Form supports `tel` type validation. [#56533](https://github.com/ant-design/ant-design/pull/56533) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 Fix Badge `ref` not working when using `text` property. [#56532](https://github.com/ant-design/ant-design/pull/56532) [@zombieJ](https://github.com/zombieJ)
- 🆕 Calendar and DatePicker `locale` configuration now supports partial content filling. [#56376](https://github.com/ant-design/ant-design/pull/56376) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix ConfigProvider `theme.cssVar` configuration not working for icons. [#56504](https://github.com/ant-design/ant-design/pull/56504) [@seanparmelee](https://github.com/seanparmelee)
- 🐞 Fix Collapse `items` semantic properties not working. [#56517](https://github.com/ant-design/ant-design/pull/56517) [@zombieJ](https://github.com/zombieJ)
- Modal
- 🆕 Modal supports `focusable.trap` to configure whether to lock focus within the Modal. [#56500](https://github.com/ant-design/ant-design/pull/56500) [@zombieJ](https://github.com/zombieJ)
- 🛠 Remove useless DOM structure from Modal and optimize focus capture to prevent accidental focus escape outside the Modal. [#56142](https://github.com/ant-design/ant-design/pull/56142) [@zombieJ](https://github.com/zombieJ)
- ConfigProvider
- 🆕 ConfigProvider supports `pagination` configuration for `totalBoundary` and `showSizeChanger` properties. [#56475](https://github.com/ant-design/ant-design/pull/56475) [@chiaweilee](https://github.com/chiaweilee)
- 🆕 ConfigProvider supports configuring Alert global icons. [#56241](https://github.com/ant-design/ant-design/pull/56241) [@guoyunhe](https://github.com/guoyunhe)
- Drawer
- 🆕 Drawer adds `focusable` to configure focus behavior after opening, supporting focus locking within the container and focus returning after closing. [#56463](https://github.com/ant-design/ant-design/pull/56463) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix Drawer `size` definition not supporting string type. [#56358](https://github.com/ant-design/ant-design/pull/56358) [@ug-hero](https://github.com/ug-hero)
- 🐞 Fix Image nested in Modal cannot be closed sequentially with Esc. [#56386](https://github.com/ant-design/ant-design/pull/56386) [@aojunhao123](https://github.com/aojunhao123)
- 🆕 Pagination supports `size` property. [#56009](https://github.com/ant-design/ant-design/pull/56009) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Breadcrumb supports `dropdownIcon` customization. [#56250](https://github.com/ant-design/ant-design/pull/56250) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Checkbox.Group supports `role` configuration. [#56126](https://github.com/ant-design/ant-design/pull/56126) [@Pareder](https://github.com/Pareder)
- 💄 Mentions fix invalid style `padding: undefined` in different sizes. [#56564](https://github.com/ant-design/ant-design/pull/56564) [@li-jia-nan](https://github.com/li-jia-nan)
- 🐞 Fix Select clear button alignment issue when `size="small"`. [#56525](https://github.com/ant-design/ant-design/pull/56525) [@QDyanbing](https://github.com/QDyanbing)
## 6.1.4
`2026-01-05`
- 🐞 Fix Select with multiple `aria-` attributes in DOM. [#56451](https://github.com/ant-design/ant-design/pull/56451) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix Table where hidden measure headers could mount interactive filter dropdowns and trigger unexpected close events when `scroll.y` is enabled. [#56425](https://github.com/ant-design/ant-design/pull/56425) [@QDyanbing](https://github.com/QDyanbing)
## 6.1.3
`2025-12-29`
- 🐞 Fix Drawer.PurePanel failing to respond to mouse interactions. [#56387](https://github.com/ant-design/ant-design/pull/56387) [@wanpan11](https://github.com/wanpan11)
- 🐞 Fix Select `options` props leaking to DOM elements and causing React unknown-prop warnings. [#56341](https://github.com/ant-design/ant-design/pull/56341) [@afc163](https://github.com/afc163)
## 6.1.2
`2025-12-24`
- 🐞 Button fix missing wave effect and the issue where the component could not show Dropdown on hover immediately after clicking. [#56273](https://github.com/ant-design/ant-design/pull/56273) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix Form.List with `useWatch` causing double rendering on item removal, with the first render showing an incorrect intermediate state. [#56319](https://github.com/ant-design/ant-design/pull/56319) [@QDyanbing](https://github.com/QDyanbing)
- 💄 Breadcrumb fix style issue when using a custom `itemRender`. [#56253](https://github.com/ant-design/ant-design/pull/56253) [@guoyunhe](https://github.com/guoyunhe)
- Transfer
- 💄 Remove Transfer className for the selected state when the component is `disabled`. [#56316](https://github.com/ant-design/ant-design/pull/56316) [@zenggpzqbx](https://github.com/zenggpzqbx)
- 🐞 Transfer prioritize using the `disabled` property of the component. [#56280](https://github.com/ant-design/ant-design/pull/56280) [#56093](https://github.com/ant-design/ant-design/pull/56093) [@zenggpzqbx](https://github.com/zenggpzqbx)
- Select
- 🐞 Fix Select missing semantic DOM names. [#56322](https://github.com/ant-design/ant-design/pull/56322) [@seanparmelee](https://github.com/seanparmelee)
- 🐞 Fix Select wrong hover cursor style when in search mode. [#56130](https://github.com/ant-design/ant-design/pull/56130) [@fpsqdb](https://github.com/fpsqdb)
- 🐞 Fix Select cursor style when disabled with `showSearch` enabled. [#56340](https://github.com/ant-design/ant-design/pull/56340) [@QDyanbing](https://github.com/QDyanbing)
- 💄 Card fix style issue where an unexpected border radius is displayed when using `Card.Grid` without a header. [#56214](https://github.com/ant-design/ant-design/pull/56214) [@DDDDD12138](https://github.com/DDDDD12138)
- 💄 Tag deepen default background to improve borderless contrast. [#56326](https://github.com/ant-design/ant-design/pull/56326) [@QDyanbing](https://github.com/QDyanbing)
- ⌨ Segmented fix duplicate `role` and unnecessary `aria-` attributes on items. [#56278](https://github.com/ant-design/ant-design/pull/56278) [@aojunhao123](https://github.com/aojunhao123)
## 6.1.1
`2025-12-15`
- 🐞 Fix DatePicker cannot support webpack 4: Can't resolve '@rc-component/picker/locale/en_US'. [#56219](https://github.com/ant-design/ant-design/pull/56219) [@afc163](https://github.com/afc163)
- 🐞 Fix ColorPicker inconsistent input heights. [#56220](https://github.com/ant-design/ant-design/pull/56220) [@ug-hero](https://github.com/ug-hero)
- 🐞 Fix notification default background color not white when cssVar is disabled. [#56169](https://github.com/ant-design/ant-design/pull/56169) [@wanpan11](https://github.com/wanpan11)
- 🐞 Fix Input border missing when focused on Space.Compact with `allowClear` prop. [#56105](https://github.com/ant-design/ant-design/pull/56105) [@tuzixiangs](https://github.com/tuzixiangs)
- 🐞 Fix vertical Splitter incorrect collapse behavior in RTL mode, RTL flipping is now applied only to horizontal layouts [#56179](https://github.com/ant-design/ant-design/pull/56179) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 Fix Result not passing through `data-*` and `aria-*` attributes to the root DOM element. [#56165](https://github.com/ant-design/ant-design/pull/56165) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 MISC: `theme.cssVar.prefix` and `theme.cssVar.key` now respect empty string value. [#56146](https://github.com/ant-design/ant-design/pull/56146) [@QDyanbing](https://github.com/QDyanbing)
- 💄 Lift Breadcrumb link style priority. [#56137](https://github.com/ant-design/ant-design/pull/56137) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 Fix ConfigProvider `closable.placement` not working. [#55985](https://github.com/ant-design/ant-design/pull/55985) [@meet-student](https://github.com/meet-student)
- 🐞 Fix Form `onValuesChange` params missing Form.List nested content. [#56129](https://github.com/ant-design/ant-design/pull/56129) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix Select `selectorBg` token not working. [#56052](https://github.com/ant-design/ant-design/pull/56052) [@ug-hero](https://github.com/ug-hero)
- 🐞 Fix Upload incorrect progress position style. [#56194](https://github.com/ant-design/ant-design/pull/56194) [@QDyanbing](https://github.com/QDyanbing)
## 6.1.0
`2025-12-08`
- 🆕 ConfigProvider supports configuring the `trigger` property for Tooltip, Popover, and Popconfirm. [#55932](https://github.com/ant-design/ant-design/pull/55932) [@aojunhao123](https://github.com/aojunhao123)
- 🆕 Alert add semantic close button element. [#55815](https://github.com/ant-design/ant-design/pull/55815) [@coding-ice](https://github.com/coding-ice)
- Drawer
- 🆕 Drawer add semantic close button element. [#55816](https://github.com/ant-design/ant-design/pull/55816) [@coding-ice](https://github.com/coding-ice)
- 🆕 Drawer add boolean type setting for `resizable`. [#55861](https://github.com/ant-design/ant-design/pull/55861) [@cactuser-Lu](https://github.com/cactuser-Lu)
- Select
- 🆕 Select add multi-field search functionality to `optionFilterProp`. [#56057](https://github.com/ant-design/ant-design/pull/56057) [@ug-hero](https://github.com/ug-hero)
- 🐞 Fix Select input cursor displayed in non-search mode. [#56067](https://github.com/ant-design/ant-design/pull/56067) [@afc163](https://github.com/afc163)
- 🐞 Fix the「Select」option was not enabled when Select contained interactive content. [#56054](https://github.com/ant-design/ant-design/pull/56054) [@yoyo837](https://github.com/yoyo837)
- 🐞 Fix Table `cellFontSizeSM` and `cellFontSizeLG` tokens not working. [#55770](https://github.com/ant-design/ant-design/pull/55770) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 Fix Button tokens (primaryColor, dangerColor, defaultHoverBg, defaultActiveBg) not working with specific variants (solid, outlined, dashed). [#55934](https://github.com/ant-design/ant-design/pull/55934) [@tuzixiangs](https://github.com/tuzixiangs)
- 💄 Fix Menu item styles not taking effect. [#56041](https://github.com/ant-design/ant-design/pull/56041) [@Wxh16144](https://github.com/Wxh16144)
- 🛠 MISC: `@ant-design/react-slick` remove `classnames`. [#56080](https://github.com/ant-design/ant-design/pull/56080) [@yoyo837](https://github.com/yoyo837)
- 🛠 MISC: Migrate `rc-overflow` to `@rc-component/overflow`, `rc-virtual-list` to `@rc-component/virtual-list` in order to remove `rc-util`. [#56074](https://github.com/ant-design/ant-design/pull/56074) [@yoyo837](https://github.com/yoyo837)
- TypeScript
- 🤖 Alert now exports ErrorBoundaryProps type. [#55974](https://github.com/ant-design/ant-design/pull/55974) [@guoyunhe](https://github.com/guoyunhe)
- 🤖 ConfigProvider supports passing a function as a Table `rowKey`. [#56095](https://github.com/ant-design/ant-design/pull/56095) [@li-jia-nan](https://github.com/li-jia-nan)
- 🤖 The `title` attribute of the notification has been changed to be optional. [#56027](https://github.com/ant-design/ant-design/pull/56027) [@afc163](https://github.com/afc163)
## 6.0.1
`2025-12-02`
- Flex
- 🐞 Fix Flex cannot pass `0` for `flex` property. [#55829](https://github.com/ant-design/ant-design/pull/55829) [@li-jia-nan](https://github.com/li-jia-nan)
- 🐞 Fix Flex cannot pass `0` for `gap` property. [#55803](https://github.com/ant-design/ant-design/pull/55803) [@li-jia-nan](https://github.com/li-jia-nan)
- Input
- 🐞 Fix Input `colorText` token does not work with `filled` variant without affix. [#56019](https://github.com/ant-design/ant-design/pull/56019) [@ug-hero](https://github.com/ug-hero)
- 🐞 Fix Input.OTP empty slots can be skipped when typing. [#56001](https://github.com/ant-design/ant-design/pull/56001) [@aojunhao123](https://github.com/aojunhao123)
- 🐞 Fix Anchor scroll problem when click same link rapidly. [#55814](https://github.com/ant-design/ant-design/pull/55814) [@tuzixiangs](https://github.com/tuzixiangs)
- 🐞 Fix Button hover text color in `solid` variant. [#55825](https://github.com/ant-design/ant-design/pull/55825) [@andriib-ship-it](https://github.com/andriib-ship-it)
- 🐞 Fix Cascader page scroll to top on first open with defaultValue. [#55890](https://github.com/ant-design/ant-design/pull/55890) [@tuzixiangs](https://github.com/tuzixiangs)
- 🐞 Fix DatePicker `borderRadiusSM` and `borderRadiusLG` token not working bug. [#56018](https://github.com/ant-design/ant-design/pull/56018) [@ug-hero](https://github.com/ug-hero)
- 🐞 Fix InputNumber text clipping bug with ColorPicker. [#55966](https://github.com/ant-design/ant-design/pull/55966) [@DDDDD12138](https://github.com/DDDDD12138)
- 🐞 Fix Select text color for search input in dark mode. [#55914](https://github.com/ant-design/ant-design/pull/55914) [@divyeshagrawal](https://github.com/divyeshagrawal)
- 🐞 Fix Splitter failing to fill its container when the sum of panel proportions is not 1. [#56025](https://github.com/ant-design/ant-design/pull/56025) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix Wave memory leak risk since RAF not clean up. [#55962](https://github.com/ant-design/ant-design/pull/55962) [@Copilot](https://github.com/Copilot)
- 🐞 Fix Modal/Image/Drawer that the `colorBgMask` token does not take effect. [#56031](https://github.com/ant-design/ant-design/pull/56031) [@ug-hero](https://github.com/ug-hero)
- 💄 Fix ConfigProvider default not config `theme.hashed` is `true` which will cause style conflict with multiple versions. [#55880](https://github.com/ant-design/ant-design/pull/55880) [@zombieJ](https://github.com/zombieJ)
- 💄 Fix Layout.Sider styles lost when zeroRuntime enabled. [#55864](https://github.com/ant-design/ant-design/pull/55864) [@wanpan11](https://github.com/wanpan11)
- 🛠 MISC: Fix that could not build with pnpm `hoist: false`. [#55938](https://github.com/ant-design/ant-design/pull/55938) [@afc163](https://github.com/afc163)
- TypeScript
- 🤖 Fix ConfigProvider type missing for Table `className` and `styles` config. [#55984](https://github.com/ant-design/ant-design/pull/55984) [@meet-student](https://github.com/meet-student)
- 🤖 Fix DatePicker props type definition. [#55826](https://github.com/ant-design/ant-design/pull/55826) [@divyeshagrawal](https://github.com/divyeshagrawal)
## 6.0.0
`2025-11-22`
🏆 Ant Design 6.0.0 is released.
#### Read it before migration
🌟 If you want to migrate to Ant Design 6.0, please check [V5 to V6](/docs/react/migration-v6).
#### Major Changes
- 🔥 Semantic structure, Refer to [Discover the Delicate Beauty of Components with Semantic Design](/docs/blog/semantic-beauty) for details.
🔥 antd components support semantic structure and ConfigProvider config, spearheaded by @thinkasany .
- feat(Result): support `classNames` and `styles` for component and ConfigProvider [#52171](https://github.com/ant-design/ant-design/pull/52171)
- feat(Statistic): support `classNames` and `styles` for component and ConfigProvider [#52141](https://github.com/ant-design/ant-design/pull/52141)
- feat(Collapse): support `classNames` and `styles` for component and ConfigProvider [#52258](https://github.com/ant-design/ant-design/pull/52258)
- feat(Badge.Ribbon): support ConfigProvider [#52303](https://github.com/ant-design/ant-design/pull/52303)
- feat(Segmented): support `classNames` and `styles` for component and ConfigProvider [#52376](https://github.com/ant-design/ant-design/pull/52376)
- feat(Modal): support `classNames` and `styles` for component and ConfigProvider [#52340](https://github.com/ant-design/ant-design/pull/52340)
- feat(Alert): support `classNames` and `styles` for component and ConfigProvider [#52669](https://github.com/ant-design/ant-design/pull/52669)
- feat(Skeleton): support `classNames` and `styles` [#52470](https://github.com/ant-design/ant-design/pull/52470) [@coding-ice](https://github.com/coding-ice)
- feat(Notification): support `classNames` and `styles` for component and ConfigProvider [#52759](https://github.com/ant-design/ant-design/pull/52759)
- feat(Tag): support `classNames` and `styles` for component and ConfigProvider [#52764](https://github.com/ant-design/ant-design/pull/52764)
- feat(Affix): support `classNames` and `styles` for component and ConfigProvider [#52745](https://github.com/ant-design/ant-design/pull/52745)
- feat(Checkbox): support `classNames` and `styles` for component and ConfigProvider [#52781](https://github.com/ant-design/ant-design/pull/52781)
- feat(Radio): support `classNames` and `styles` for component and ConfigProvider [#52780](https://github.com/ant-design/ant-design/pull/52780)
- feat(Message): support `classNames` and `styles` for component and ConfigProvider [#52793](https://github.com/ant-design/ant-design/pull/52793)
- feat(Watermark): support `classNames` and `styles` for component and ConfigProvider [#52811](https://github.com/ant-design/ant-design/pull/52811)
- feat(Spin): support `classNames` and `styles` for component and ConfigProvider [#52823](https://github.com/ant-design/ant-design/pull/52823)
- feat(Switch): support `classNames` and `styles` for component and ConfigProvider [#52849](https://github.com/ant-design/ant-design/pull/52849)
- feat(Breadcrumb): support `classNames` and `styles` for component and ConfigProvider [#52859](https://github.com/ant-design/ant-design/pull/52859)
- feat(Anchor): support `classNames` and `styles` for component and ConfigProvider [#52866](https://github.com/ant-design/ant-design/pull/52866)
- feat(Pagination): support `classNames` and `styles` for component and ConfigProvider [#52893](https://github.com/ant-design/ant-design/pull/52893)
- feat(Tabs): support `classNames` and `styles` for component and ConfigProvider [#52895](https://github.com/ant-design/ant-design/pull/52895)
- feat(Timeline): support `classNames` and `styles` for component and ConfigProvider [#52976](https://github.com/ant-design/ant-design/pull/52976)
- feat(Mentions): support `classNames` and `styles` for component and ConfigProvider [#52961](https://github.com/ant-design/ant-design/pull/52961)
- feat(Upload): support `classNames` and `styles` for component and ConfigProvider [#52972](https://github.com/ant-design/ant-design/pull/52972)
- feat(Tour): support ConfigProvider [#52250](https://github.com/ant-design/ant-design/pull/52250)
- feat(Button): support `classNames` and `styles` for component and ConfigProvider [#53055](https://github.com/ant-design/ant-design/pull/53055)
- feat(Select): support `classNames` and `styles` for component and ConfigProvider [#52948](https://github.com/ant-design/ant-design/pull/52948)
- feat(Image): support `classNames` and `styles` for component and ConfigProvider [#53028](https://github.com/ant-design/ant-design/pull/53028)
- feat(Tree): support `classNames` and `styles` for component and ConfigProvider [#53174](https://github.com/ant-design/ant-design/pull/53174)
- feat(AutoComplete): support `classNames` and `styles` for component and ConfigProvider [#53150](https://github.com/ant-design/ant-design/pull/53150)
- feat(Splitter): support `classNames` and `styles` [#53225](https://github.com/ant-design/ant-design/pull/53225) [@wanpan11](https://github.com/wanpan11)
- feat(Form): support `classNames` and `styles` for component and ConfigProvider [#53226](https://github.com/ant-design/ant-design/pull/53226)
- feat(Calendar): support `classNames` and `styles` for component and ConfigProvider [#53159](https://github.com/ant-design/ant-design/pull/53159)
- feat(TreeSelect): support `classNames` and `styles` for component and ConfigProvider [#53229](https://github.com/ant-design/ant-design/pull/53229)
- feat(ColorPicker): support `classNames` and `styles` for component and ConfigProvider [#53303](https://github.com/ant-design/ant-design/pull/53303)
- feat(Transfer): support `classNames` and `styles` for component and ConfigProvider [#53429](https://github.com/ant-design/ant-design/pull/53429) [@zombieJ](https://github.com/zombieJ)
- feat(QRCode): support ConfigProvider [#52172](https://github.com/ant-design/ant-design/pull/52172)
- feat(Progress): support `classNames` and `styles` for component and ConfigProvider [#53535](https://github.com/ant-design/ant-design/pull/53535) [@zombieJ](https://github.com/zombieJ)
- feat(TimePicker, DatePicker): support `classNames` and `styles` for components and ConfigProvider [#53489](https://github.com/ant-design/ant-design/pull/53489)
- feat(Menu): support `classNames` and `styles` for component and ConfigProvider [#53324](https://github.com/ant-design/ant-design/pull/53324)
- feat(Dropdown): support `classNames` and `styles` for component and ConfigProvider [#53272](https://github.com/ant-design/ant-design/pull/53272)
- feat(Cascader): support `classNames` and `styles` for component and ConfigProvider [#53694](https://github.com/ant-design/ant-design/pull/53694)
- feat(InputNumber): support `classNames` and `styles` for component and ConfigProvider [#53698](https://github.com/ant-design/ant-design/pull/53698)
- feat(Steps): support `classNames` and `styles` for component and ConfigProvider [#53789](https://github.com/ant-design/ant-design/pull/53789) [@zombieJ](https://github.com/zombieJ)
- feat(Table): support `classNames` and `styles` for component and ConfigProvider [#53659](https://github.com/ant-design/ant-design/pull/53659)
- feat(Divider): support `classNames` and `styles` for component and ConfigProvider [#53890](https://github.com/ant-design/ant-design/pull/53890)
- feat(Input): support semantic DOM [#53958](https://github.com/ant-design/ant-design/pull/53958) [@aojunhao123](https://github.com/aojunhao123)
- feat(FloatButton): support semantic structure and support ConfigProvider to pass related props [#54145](https://github.com/ant-design/ant-design/pull/54145) [@zombieJ](https://github.com/zombieJ)
- refactor(Select): support semantic structure [#55430](https://github.com/ant-design/ant-design/pull/55430) [@zombieJ](https://github.com/zombieJ)
🔥 antd components support dynamic semantic structure generation via function, spearheaded by @meet-student .
- feat(button): Support better customization with semantic classNames/styles as function [#54813](https://github.com/ant-design/ant-design/pull/54813)
- feat(input): Support better customization with semantic classNames/styles as function [#54919](https://github.com/ant-design/ant-design/pull/54919)
- feat(float-button): Support better customization with semantic classNames/styles as function [#54917](https://github.com/ant-design/ant-design/pull/54917)
- feat(divider): Support better customization with semantic classNames/styles as function [#54949](https://github.com/ant-design/ant-design/pull/54949)
- feat(breadcrumb): Support better customization with semantic classNames/styles as function [#54950](https://github.com/ant-design/ant-design/pull/54950)
- feat(anchor): Support better customization with semantic classNames/styles as function [#54948](https://github.com/ant-design/ant-design/pull/54948)
- feat(masonry): Support better customization with semantic classNames/styles as function [#55032](https://github.com/ant-design/ant-design/pull/55032)
- feat(Progress): Support better customization with semantic classNames & styles [#55058](https://github.com/ant-design/ant-design/pull/55058) [@li-jia-nan](https://github.com/li-jia-nan)
- feat(menu): Support better customization with semantic classNames/styles as function [#54955](https://github.com/ant-design/ant-design/pull/54955)
- feat(space): Support better customization with semantic classNames/styles as function [#55031](https://github.com/ant-design/ant-design/pull/55031) [@hcjlxl](https://github.com/hcjlxl)
- feat(tabs): Support better customization with semantic classNames/styles as function [#54958](https://github.com/ant-design/ant-design/pull/54958)
- feat(splitter): Support better customization with semantic classNames/styles as function [#55013](https://github.com/ant-design/ant-design/pull/55013) [@hcjlxl](https://github.com/hcjlxl)
- feat(pagination): Support better customization with semantic classNames/styles as function [#54957](https://github.com/ant-design/ant-design/pull/54957)
- feat(steps): Support better customization with semantic classNames/styles as function [#54956](https://github.com/ant-design/ant-design/pull/54956)
- feat(dropdown): Support better customization with semantic classNames/styles as function [#55114](https://github.com/ant-design/ant-design/pull/55114) [@Arktomson](https://github.com/Arktomson)
- feat(checkbox_radio): Support better customization with semantic classNames/styles as function [#55056](https://github.com/ant-design/ant-design/pull/55056)
- feat(auto-complete): Support better customization with semantic classNames/styles as function [#54959](https://github.com/ant-design/ant-design/pull/54959)
- feat(form): Support better customization with semantic classNames/styles as function [#55126](https://github.com/ant-design/ant-design/pull/55126)
- feat(date-picker_time-picker): Support better customization with semantic classNames/styles as function [#54969](https://github.com/ant-design/ant-design/pull/54969)
- feat(InputNumber): Support better customization with semantic classNames/styles as function [#54996](https://github.com/ant-design/ant-design/pull/54996) [@zjr222](https://github.com/zjr222)
- feat(input-otp_textarea_search): Support better customization with semantic classNames/styles as function [#55109](https://github.com/ant-design/ant-design/pull/55109) [@Arktomson](https://github.com/Arktomson)
- feat(mentions): Support better customization with semantic classNames/styles as function [#54963](https://github.com/ant-design/ant-design/pull/54963)
- feat(select): Support better customization with semantic classNames/styles as function [#55101](https://github.com/ant-design/ant-design/pull/55101) [@Linkodt](https://github.com/Linkodt)
- feat(slider): Support better customization with semantic classNames/styles as function [#54965](https://github.com/ant-design/ant-design/pull/54965)
- feat(switch): Support better customization with semantic classNames/styles as function [#54994](https://github.com/ant-design/ant-design/pull/54994) [@xkhanhan](https://github.com/xkhanhan)
- feat(transfer): Support better customization with semantic classNames/styles as function [#54966](https://github.com/ant-design/ant-design/pull/54966)
- feat(upload): Support better customization with semantic classNames/styles as function [#54968](https://github.com/ant-design/ant-design/pull/54968)
- feat(calendar): Support better customization with semantic classNames/styles as function [#54978](https://github.com/ant-design/ant-design/pull/54978)
- feat(descriptions): Support better customization with semantic classNames/styles [#55118](https://github.com/ant-design/ant-design/pull/55118) [@tanjiahao24](https://github.com/tanjiahao24)
- feat(empty): Support better customization with semantic classNames/styles as function [#55007](https://github.com/ant-design/ant-design/pull/55007) [@Susuperli](https://github.com/Susuperli)
- refactor: semantic of Descriptions [#55190](https://github.com/ant-design/ant-design/pull/55190)
- feat(qr-code): Support better customization with semantic classNames/styles as function [#54982](https://github.com/ant-design/ant-design/pull/54982)
- feat(statistic): Support better customization with semantic classNames/styles as function [#55117](https://github.com/ant-design/ant-design/pull/55117) [@Arktomson](https://github.com/Arktomson)
- feat(table): Support better customization with semantic classNames/styles as function [#54983](https://github.com/ant-design/ant-design/pull/54983)
- feat(tag): Support better customization with semantic classNames/styles as function [#54984](https://github.com/ant-design/ant-design/pull/54984)
- feat(alert): Support better customization with semantic classNames/styles [#55060](https://github.com/ant-design/ant-design/pull/55060) [@ccc1018](https://github.com/ccc1018)
- feat(result): Support better customization with semantic classNames/styles as function [#55044](https://github.com/ant-design/ant-design/pull/55044) [@ccc1018](https://github.com/ccc1018)
- feat(Drawer): Support better customization with semantic classNames & styles [#55096](https://github.com/ant-design/ant-design/pull/55096) [@li-jia-nan](https://github.com/li-jia-nan)
- feat(Modal): Support better customization with semantic classNames & styles [#55081](https://github.com/ant-design/ant-design/pull/55081) [@li-jia-nan](https://github.com/li-jia-nan)
- feat(notification): Support better customization with semantic classNames/styles as function [#55021](https://github.com/ant-design/ant-design/pull/55021) [@GinWU05](https://github.com/GinWU05)
- feat(spin): Support better customization with semantic classNames/styles as function [#55157](https://github.com/ant-design/ant-design/pull/55157) [@Susuperli](https://github.com/Susuperli)
- feat(card): Support better customization with semantic classNames/styles as function [#55161](https://github.com/ant-design/ant-design/pull/55161) [@lovelts](https://github.com/lovelts)
- feat(collapse): Support better customization with semantic classNames/styles as function [#54979](https://github.com/ant-design/ant-design/pull/54979)
- feat(message): support better customization with semantic classNames/styles [#55054](https://github.com/ant-design/ant-design/pull/55054) [@nmsn](https://github.com/nmsn)
- feat(image): Support better customization with semantic classNames/styles as function [#54980](https://github.com/ant-design/ant-design/pull/54980)
- feat(segmented): Support better customization with semantic classNames/styles as function [#55119](https://github.com/ant-design/ant-design/pull/55119) [@Arktomson](https://github.com/Arktomson)
- feat(timeline): Support better customization with semantic classNames/styles as function [#54985](https://github.com/ant-design/ant-design/pull/54985)
- refactor: semantic of message and notification [#55199](https://github.com/ant-design/ant-design/pull/55199)
- feat(tour): Support better customization with semantic classNames/styles as function [#54987](https://github.com/ant-design/ant-design/pull/54987)
- feat(tree): Support better customization with semantic classNames/styles as function [#54988](https://github.com/ant-design/ant-design/pull/54988)
- feat(Popover/Tooltip/Popconfirm): Support better customization with semantic classNames/styles as function [#54986](https://github.com/ant-design/ant-design/pull/54986)
- feat(Skeleton): Support better customization with semantic classNames & styles [#55099](https://github.com/ant-design/ant-design/pull/55099) [@li-jia-nan](https://github.com/li-jia-nan)
- feat(cascader): Support better customization with semantic classNames/styles as function [#54960](https://github.com/ant-design/ant-design/pull/54960)
- feat(color-picker): Support better customization with semantic classNames/styles as function [#54962](https://github.com/ant-design/ant-design/pull/54962)
- feat(badge): Support better customization with semantic classNames/styles as function [#54977](https://github.com/ant-design/ant-design/pull/54977)
- feat(tree-select): Support better customization with semantic classNames/styles as function [#54967](https://github.com/ant-design/ant-design/pull/54967)
- feat(CheckableTagGroup): Support better customization with semantic classNames/styles as function [#55796](https://github.com/ant-design/ant-design/pull/55796)
- 🔥 New Masonry component. [#52162](https://github.com/ant-design/ant-design/pull/52162) [@OysterD3](https://github.com/OysterD3)
- ConfigProvider
- 🆕 ConfigProvider support Table `rowKey` global config. [#52751](https://github.com/ant-design/ant-design/pull/52751) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 ConfigProvider support Card.Meta config. [#52214](https://github.com/ant-design/ant-design/pull/52214) [@thinkasany](https://github.com/thinkasany)
- 🆕 ConfigProvider support arrow for Tooltip, Popover, Popconfirm. [#52434](https://github.com/ant-design/ant-design/pull/52434) [@thinkasany](https://github.com/thinkasany)
- 🆕 ConfigProvider support `root` config for Space. [#52248](https://github.com/ant-design/ant-design/pull/52248) [@thinkasany](https://github.com/thinkasany)
- Tooltip
- 🔥 ConfigProvider supports configuring `tooltip.unique` to enable Tooltip smooth movement. [#55154](https://github.com/ant-design/ant-design/pull/55154) [@zombieJ](https://github.com/zombieJ)
- ⚡️ Optimize Tooltip dev render performance(~40%) to enhance developer experience. [#53844](https://github.com/ant-design/ant-design/pull/53844) [@zombieJ](https://github.com/zombieJ)
- Input
- 🔥 InputNumber support `mode="spinner"`. [#55592](https://github.com/ant-design/ant-design/pull/55592) [@guoyunhe](https://github.com/guoyunhe)
- 🗑 Input.Search refactor to remove `addon*` code and use Space.Compact instead. [#55705](https://github.com/ant-design/ant-design/pull/55705) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 Fix Input.TextArea `styles.textarea` unable to override built-in styles. [#55579](https://github.com/ant-design/ant-design/pull/55579) [@meet-student](https://github.com/meet-student)
- 🆕 Pagination quick jumper now accept numberic value only. [#55700](https://github.com/ant-design/ant-design/pull/55700) [@afc163](https://github.com/afc163)
- Mentions
- 🛠 Refactor Mentions DOM structure to support `suffix` semantic and `size` props. [#55638](https://github.com/ant-design/ant-design/pull/55638) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix Mentions `autoResize=false` can not drag to resize the box. [#54039](https://github.com/ant-design/ant-design/pull/54039) [@jin19980928](https://github.com/jin19980928)
- 🆕 Watermark support `onRemove` callback when delete by manully. [#55551](https://github.com/ant-design/ant-design/pull/55551) [@984507092](https://github.com/984507092)
- 🆕 Breadcrumb supports ConfigProvider `separator` global configuration. [#54680](https://github.com/ant-design/ant-design/pull/54680) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Alert `closable` supports onClose and afterClose methods. [#54735](https://github.com/ant-design/ant-design/pull/54735) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Radio.Group supports `vertical` layout syntax sugar. [#54727](https://github.com/ant-design/ant-design/pull/54727) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- Cascader
- 🆕 Cascader support `aria-*` & `data-*` props. [#53910](https://github.com/ant-design/ant-design/pull/53910) [@kiner-tang](https://github.com/kiner-tang)
- 🆕 Cascader.Panel adds optionRender to allow custom option rendering. [#54843](https://github.com/ant-design/ant-design/pull/54843) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Upload `accept` config supports custom filtering logic. [#55543](https://github.com/ant-design/ant-design/pull/55543) [@zombieJ](https://github.com/zombieJ)
- Rate
- 🆕 Rate supports `size` to configure dimensions. [#55028](https://github.com/ant-design/ant-design/pull/55028) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Rate `tooltips` support all config. [07b1610](https://github.com/ant-design/ant-design/commit/07b1610) [@Jerryqun](https://github.com/Jerryqun)
- 🆕 Select support `onActive` keyboard and mouse interaction. [#53931](https://github.com/ant-design/ant-design/pull/53931) [@Wxh16144](https://github.com/Wxh16144)
- 🆕 Typography `copyable` supports HTTP environment. [#55073](https://github.com/ant-design/ant-design/pull/55073) [@JeeekXY](https://github.com/JeeekXY)
- Form
- 🔥 Form `useWatch` support dynamic name path. [#54260](https://github.com/ant-design/ant-design/pull/54260) [@zombieJ](https://github.com/zombieJ)
- 🆕 Form now excludes unregistered field values from `Form.List` when getting values. [#55526](https://github.com/ant-design/ant-design/pull/55526) [@crazyair](https://github.com/crazyair)
- ⚡️ Optimize Form `useWatch` perf when lots of Form.Item unmounted. [#54212](https://github.com/ant-design/ant-design/pull/54212) [@zombieJ](https://github.com/zombieJ)
- 🆕 Flex support `orientation` for layout. [#53648](https://github.com/ant-design/ant-design/pull/53648) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- DatePicker
- 🆕 DatePicker semantic structure adds panel `container` support. [#55388](https://github.com/ant-design/ant-design/pull/55388) [@meet-student](https://github.com/meet-student)
- 🆕 DatePicker adds `previewValue` to control whether to display preview value in input when hovering over options. [#55258](https://github.com/ant-design/ant-design/pull/55258) [@meet-student](https://github.com/meet-student)
- 🐞 Fix DatePicker `onChange` parameter `dateString` returning incorrect value when clearing. [#55155](https://github.com/ant-design/ant-design/pull/55155) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- Drawer
- 🆕 Drawer adds `resizable` to support drag capability. [#54883](https://github.com/ant-design/ant-design/pull/54883) [@cactuser-Lu](https://github.com/cactuser-Lu)
- 💄 Drawer mask adds blur effect. [#54707](https://github.com/ant-design/ant-design/pull/54707) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 ColorPicker `presets` support linear gradient color. [#53250](https://github.com/ant-design/ant-design/pull/53250) [@zombieJ](https://github.com/zombieJ)
- Collapse
- 🆕 Collapse `expandIconPosition` replaced with `expandIconPlacement` and use logical position to improve RTL experience. [#54311](https://github.com/ant-design/ant-design/pull/54311) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 Fix Collapse semantic structure `icon` targeting incorrect element. [#55499](https://github.com/ant-design/ant-design/pull/55499) [@thinkasany](https://github.com/thinkasany)
- 🐞 Fix Collapse dynamic modification of semantic icon not taking effect. [#55452](https://github.com/ant-design/ant-design/pull/55452) [@thinkasany](https://github.com/thinkasany)
- Table
- 🆕 Table `scrollTo` support `offset` to adjust scroll position. [#54385](https://github.com/ant-design/ant-design/pull/54385) [@zombieJ](https://github.com/zombieJ)
- 🆕 Table use `pagination.placement` instead of `pagination.position`. [#54338](https://github.com/ant-design/ant-design/pull/54338) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- ⌨️ Improve Table a11y behavior by adding `aria-description` when column is sortable. [#53087](https://github.com/ant-design/ant-design/pull/53087) [@jon-cullison](https://github.com/jon-cullison)
- 🆕 Refactor Table `column.fixed` to use `start` & `end` to support logical position. [#53114](https://github.com/ant-design/ant-design/pull/53114) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix Table showing duplicate filter dropdowns and tooltips when using `sticky` or `scroll.y`. Fix Table column headers not displaying during initial render phase. [#54910](https://github.com/ant-design/ant-design/pull/54910) [@afc163](https://github.com/afc163)
- 🐞 Fix Table data not refreshing when dynamically modifying `childrenColumnName`. [#55559](https://github.com/ant-design/ant-design/pull/55559) [@li-jia-nan](https://github.com/li-jia-nan)
- Progress
- 🆕 Progress use `gapPlacement` instead `gapPosition` and replace `left` and `right` with `start` and `end`. [#54329](https://github.com/ant-design/ant-design/pull/54329) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 Fix Progress indicator content not updating when props change. [#55554](https://github.com/ant-design/ant-design/pull/55554) [@thinkasany](https://github.com/thinkasany)
- 🛠 Grid use CSS logical position to improve RTL experience. [#52560](https://github.com/ant-design/ant-design/pull/52560) [@li-jia-nan](https://github.com/li-jia-nan)
- Notification
- 🛠 Notification support `closable` to take `onClose` & `closeIcon` into it. [#54645](https://github.com/ant-design/ant-design/pull/54645) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Notification support custom progress bar color. [#52964](https://github.com/ant-design/ant-design/pull/52964) [@yellowryan](https://github.com/yellowryan)
- 🆕 Notification adds new `title` property to replace the `message` property, and deprecates `message`. [#52759](https://github.com/ant-design/ant-design/pull/52759) [@thinkasany](https://github.com/thinkasany)
- Image
- 🆕 Image `cover` support placement. [#54492](https://github.com/ant-design/ant-design/pull/54492) [@kiner-tang](https://github.com/kiner-tang)
- 🛠 Image remove default cover icon & text (Still can use `cover` to config). [#54379](https://github.com/ant-design/ant-design/pull/54379) [@765477020](https://github.com/765477020)
- 🐞 Fix Image preview text issue when in RTL. [#53596](https://github.com/ant-design/ant-design/pull/53596) [@aojunhao123](https://github.com/aojunhao123)
- Modal
- 🆕 Modal `closable` support `onClose` props that trigger by any type of close. [#54607](https://github.com/ant-design/ant-design/pull/54607) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 ConfigProvider support config Modal `okButtonProps` & `cancelButtonProps`. [#53684](https://github.com/ant-design/ant-design/pull/53684) [@guoyunhe](https://github.com/guoyunhe)
- 🛠 Modal adjust DOM `className` to be align with semantic structure standard. [#54472](https://github.com/ant-design/ant-design/pull/54472) [@thinkasany](https://github.com/thinkasany)
- ⌨️ Apply Modal `closable.aria-*` attribute on the close button. [#53289](https://github.com/ant-design/ant-design/pull/53289) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 Fix Modal quick switch `open` state will make screen operation frozen. [#52753](https://github.com/ant-design/ant-design/pull/52753) [@zombieJ](https://github.com/zombieJ)
- Theme
- 🔥 Support `zeroRuntime` mode in `theme` prop of ConfigProvider, in order to avoid runtime style generation. [#54334](https://github.com/ant-design/ant-design/pull/54334) [@MadCcc](https://github.com/MadCcc)
- 🆕 MISC: CSS-in-JS support `autoPrefixTransformer` to add browser style prefix. [#54427](https://github.com/ant-design/ant-design/pull/54427) [@zombieJ](https://github.com/zombieJ)
- 🆕 Design Token export cssVar in `useToken`. [#53195](https://github.com/ant-design/ant-design/pull/53195) [@MadCcc](https://github.com/MadCcc)
- 💄 MISC: Remove mark style from reset.css. [#52974](https://github.com/ant-design/ant-design/pull/52974) [@afc163](https://github.com/afc163)
- 🔥 MISC: Use CSS variables by default. [#52671](https://github.com/ant-design/ant-design/pull/52671) [@MadCcc](https://github.com/MadCcc)
- 💄 Design Token add `colorBorderDisabled` token to unify border color in disabled state. [#52421](https://github.com/ant-design/ant-design/pull/52421) [@aojunhao123](https://github.com/aojunhao123)
- Segmented
- 🆕 Segmented support `items.tooltip`. [#54273](https://github.com/ant-design/ant-design/pull/54273) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Segmented support `orientation` for layout. [#53664](https://github.com/ant-design/ant-design/pull/53664) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🛠 Improve Segmented accessibility. [#52618](https://github.com/ant-design/ant-design/pull/52618) [@aojunhao123](https://github.com/aojunhao123)
- Tabs
- 🆕 Tabs use `tabPlacement` instead `tabPosition` and replace `left` and `right` with `start` and `end`. [#54358](https://github.com/ant-design/ant-design/pull/54358) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 💄 Tabs remove active text shadow. [#53617](https://github.com/ant-design/ant-design/pull/53617) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 Fix Tabs focus behavior for empty TabPane to improve accessibility. [#52856](https://github.com/ant-design/ant-design/pull/52856) [@aojunhao123](https://github.com/aojunhao123)
- 🛠 Remove Tabs deprecated API. [#52768](https://github.com/ant-design/ant-design/pull/52768) [@aojunhao123](https://github.com/aojunhao123)
- 🛠 Replace Steps `labelPlacement` to `titlePlacement` to unify the API. [#53873](https://github.com/ant-design/ant-design/pull/53873) [@zombieJ](https://github.com/zombieJ)
- Space
- 🛠 Space use `separator` instead of `split`. [#53983](https://github.com/ant-design/ant-design/pull/53983) [@thinkasany](https://github.com/thinkasany)
- 🛠 Space use `orientation` instead of `direction`. [#53669](https://github.com/ant-design/ant-design/pull/53669) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Spin support `styles.wrapper`. [#53448](https://github.com/ant-design/ant-design/pull/53448) [@crazyair](https://github.com/crazyair)
- Splitter
- 🆕 Splitter use `orientation` instead of `layout` and support `vertical` prop. [#53670](https://github.com/ant-design/ant-design/pull/53670) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Splitter support customize handle elements and style. [#52216](https://github.com/ant-design/ant-design/pull/52216) [@wanpan11](https://github.com/wanpan11)
- Tour
- 🐞 Fix Tour DOM structure `panel` className typo. [#55178](https://github.com/ant-design/ant-design/pull/55178) [@thinkasany](https://github.com/thinkasany)
- 🐞 Fix Tour popup not follow when scroll. [#53140](https://github.com/ant-design/ant-design/pull/53140) [@dependabot](https://github.com/dependabot)
- Button
- 🆕 Button `iconPosition` replaced with `iconPlacement` and support logical position. [#54279](https://github.com/ant-design/ant-design/pull/54279) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🛠 Button `variant` & `color` refactor with css variables version to reduce bundle size. [#54100](https://github.com/ant-design/ant-design/pull/54100) [@zombieJ](https://github.com/zombieJ)
- 🆕 Button add custom default and dashed type button background color in disabled state. [#52839](https://github.com/ant-design/ant-design/pull/52839) [@yellowryan](https://github.com/yellowryan)
- Tag
- 🆕 Tag support CheckableTagGroup sub component. [#53256](https://github.com/ant-design/ant-design/pull/53256) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Tag custom color support variants. [#53097](https://github.com/ant-design/ant-design/pull/53097) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Tag support `disabled` and `href`. [#52229](https://github.com/ant-design/ant-design/pull/52229) [@aojunhao123](https://github.com/aojunhao123)
- 🐞 Fix Tag not updating when modifying `variant` via ConfigProvider. [#55555](https://github.com/ant-design/ant-design/pull/55555) [@thinkasany](https://github.com/thinkasany)
- 💄 Remove Tag `margin` style. [#52123](https://github.com/ant-design/ant-design/pull/52123) [@li-jia-nan](https://github.com/li-jia-nan)
- Timeline
- 🆕 Timeline support `titleSpan` to config the size of `title`. [#54072](https://github.com/ant-design/ant-design/pull/54072) [@zombieJ](https://github.com/zombieJ)
- 🆕 Timeline support `orientation=horizontal` layout. [#54031](https://github.com/ant-design/ant-design/pull/54031) [@zombieJ](https://github.com/zombieJ)
- 🆕 Timeline `items.position` replaced with `items.placement` and using logical position description to improve RTL experience. [#54382](https://github.com/ant-design/ant-design/pull/54382) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Transfer add `actions` prop which accept ReactNode array. [#54104](https://github.com/ant-design/ant-design/pull/54104) [@afc163](https://github.com/afc163)
- 🆕 Carousel use `dotPlacement` instead of `dotPosition` and support`start` and `end` logical position. [#54294](https://github.com/ant-design/ant-design/pull/54294) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Divider use `orientation` instead of `type` and support `vertical` syntax sugar. [#53645](https://github.com/ant-design/ant-design/pull/53645) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🛠 AutoComplete merge search related props into `showSearch`. [#54184](https://github.com/ant-design/ant-design/pull/54184) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Menu support `popupRender` for popup customization. [#53566](https://github.com/ant-design/ant-design/pull/53566) [@Zyf665](https://github.com/Zyf665)
- 🆕 Message support `pauseOnHover` that pause count down when user hover on it. [#53785](https://github.com/ant-design/ant-design/pull/53785) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 💄 `reset.css` removes IE compatibility. [#55108](https://github.com/ant-design/ant-design/pull/55108) [@thinkasany](https://github.com/thinkasany)
- 🛠 Slider support `orientation` to config layout. [#53671](https://github.com/ant-design/ant-design/pull/53671) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 💄 Remove InputNumber mobile default hidden controls. [#54900](https://github.com/ant-design/ant-design/pull/54900) [@Wxh16144](https://github.com/Wxh16144)
- 💄 Image mask adds blur effect. [#54714](https://github.com/ant-design/ant-design/pull/54714) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 💄 Modal mask adds blur effect. [#54670](https://github.com/ant-design/ant-design/pull/54670) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🛠 Deprecated List component and removed from document. [#54182](https://github.com/ant-design/ant-design/pull/54182) [@zombieJ](https://github.com/zombieJ)
- 🐞 Fix Statistic.Timer `onFinish` & `onChange` not trigger when window is inactive. [#53894](https://github.com/ant-design/ant-design/pull/53894) [@Psiphonc](https://github.com/Psiphonc)
- 🛠 Badge refactor `offset` style offset to CSS logical position. [#55245](https://github.com/ant-design/ant-design/pull/55245) [@li-jia-nan](https://github.com/li-jia-nan)
- 🛠 BackTop has been removed. [#52206](https://github.com/ant-design/ant-design/pull/52206) [@li-jia-nan](https://github.com/li-jia-nan)
- 🗑 Icon has been removed. [#52241](https://github.com/ant-design/ant-design/pull/52241) [@li-jia-nan](https://github.com/li-jia-nan)
- 🛠 Remove Dropdown.Button, please use Space.Compact instead. [#53793](https://github.com/ant-design/ant-design/pull/53793) [@Meet-student](https://github.com/Meet-student)
- 🛠 MISC: Replace `classNames` library with `clsx`. [0246702](https://github.com/ant-design/ant-design/commit/0246702) [#55164](https://github.com/ant-design/ant-design/pull/55164) [@lijianan](https://github.com/lijianan)
- 🛠 MISC: Remove MediaQueryList compatibility code for legacy browsers. [#55396](https://github.com/ant-design/ant-design/pull/55396) [@li-jia-nan](https://github.com/li-jia-nan)
- 🛠 MISC: Remove React 19 compatibility code, antd now supports React 19 by default. [#55274](https://github.com/ant-design/ant-design/pull/55274) [@li-jia-nan](https://github.com/li-jia-nan)
- 🛠 MISC: Remove `copy-to-clipboard` deps. [#54448](https://github.com/ant-design/ant-design/pull/54448) [@765477020](https://github.com/765477020)
- 🔥 MISC: Raise build target which will not support IE anymore. [#53390](https://github.com/ant-design/ant-design/pull/53390) [@zombieJ](https://github.com/zombieJ)
- 🔥 MISC: Enabled `React Compiler` in the bundled outputs `antd.js` and `antd.min.js` to improve performance. Users in CJS/ESM environments can choose to enable it as needed. For more details, refer to the [React documentation](https://react.dev/learn/react-compiler). [#55781](https://github.com/ant-design/ant-design/pull/55781) [@li-jia-nan](https://github.com/li-jia-nan)
- 🔥 MISC: Color-related components now support preset color names (e.g., `red`, `blue`, `green`, etc.). [#53241](https://github.com/ant-design/ant-design/pull/53241) [@zombieJ](https://github.com/zombieJ)
- 🌐 Add Marathi locale translation. [#55179](https://github.com/ant-design/ant-design/pull/55179) [@divyeshagrawal](https://github.com/divyeshagrawal)
- TypeScript
- 🤖 Optimize Notification `duration` definition, now disable close is `false`. [#55580](https://github.com/ant-design/ant-design/pull/55580) [@wanpan11](https://github.com/wanpan11)
## 5.x
Visit [GitHub](https://github.com/ant-design/ant-design/blob/5.x-stable/CHANGELOG.en-US.md) to read `5.x` change logs.
## 4.x
Visit [GitHub](https://github.com/ant-design/ant-design/blob/4.x-stable/CHANGELOG.en-US.md) to read `4.x` change logs.
## 3.x
Visit [GitHub](https://github.com/ant-design/ant-design/blob/3.x-stable/CHANGELOG.en-US.md) to read `3.x` change logs.
## 2.x
Visit [GitHub](https://github.com/ant-design/ant-design/blob/2.x-stable/CHANGELOG.en-US.md) to read `2.x` change logs.
## 1.11.4
Visit [GitHub](https://github.com/ant-design/ant-design/blob/1.x-stable/CHANGELOG.md) to read change logs from `0.x` to `1.x`.
---
## checkbox
Source: https://ant.design/components/checkbox.md
---
category: Components
group: Data Entry
title: Checkbox
description: Collect user's choices.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*DzgiRbW3khIAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*G3MjTYXL6AIAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
- Used for selecting multiple values from several options.
- If you use only one checkbox, it is the same as using Switch to toggle between two states. The difference is that Switch will trigger the state change directly, but Checkbox just marks the state as changed and this needs to be submitted.
## Examples
### Basic
Basic usage of checkbox.
```tsx
import React from 'react';
import { Checkbox } from 'antd';
import type { CheckboxProps } from 'antd';
const onChange: CheckboxProps['onChange'] = (e) => {
console.log(`checked = ${e.target.checked}`);
};
const App: React.FC = () => Checkbox ;
export default App;
```
### Disabled
Disabled checkbox.
```tsx
import React from 'react';
import { Checkbox, Flex } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Controlled Checkbox
Communicated with other components.
```tsx
import React, { useState } from 'react';
import { Button, Checkbox } from 'antd';
import type { CheckboxProps } from 'antd';
const App: React.FC = () => {
const [checked, setChecked] = useState(true);
const [disabled, setDisabled] = useState(false);
const toggleChecked = () => {
setChecked(!checked);
};
const toggleDisable = () => {
setDisabled(!disabled);
};
const onChange: CheckboxProps['onChange'] = (e) => {
console.log('checked = ', e.target.checked);
setChecked(e.target.checked);
};
const label = `${checked ? 'Checked' : 'Unchecked'}-${disabled ? 'Disabled' : 'Enabled'}`;
return (
<>
{label}
{!checked ? 'Check' : 'Uncheck'}
{!disabled ? 'Disable' : 'Enable'}
>
);
};
export default App;
```
### Checkbox Group
Generate a group of checkboxes from an array.
```tsx
import React from 'react';
import { Checkbox } from 'antd';
import type { CheckboxOptionType, GetProp } from 'antd';
const onChange: GetProp = (checkedValues) => {
console.log('checked = ', checkedValues);
};
const plainOptions = ['Apple', 'Pear', 'Orange'];
const options: CheckboxOptionType[] = [
{ label: 'Apple', value: 'Apple', className: 'label-1' },
{ label: 'Pear', value: 'Pear', className: 'label-2' },
{ label: 'Orange', value: 'Orange', className: 'label-3' },
];
const optionsWithDisabled: CheckboxOptionType[] = [
{ label: 'Apple', value: 'Apple', className: 'label-1' },
{ label: 'Pear', value: 'Pear', className: 'label-2' },
{ label: 'Orange', value: 'Orange', className: 'label-3', disabled: false },
];
const App: React.FC = () => (
<>
>
);
export default App;
```
### Check all
The `indeterminate` property can help you to achieve a 'check all' effect.
```tsx
import React, { useState } from 'react';
import { Checkbox, Divider } from 'antd';
import type { CheckboxProps } from 'antd';
const CheckboxGroup = Checkbox.Group;
const plainOptions = ['Apple', 'Pear', 'Orange'];
const defaultCheckedList = ['Apple', 'Orange'];
const App: React.FC = () => {
const [checkedList, setCheckedList] = useState(defaultCheckedList);
const checkAll = plainOptions.length === checkedList.length;
const indeterminate = checkedList.length > 0 && checkedList.length < plainOptions.length;
const onChange = (list: string[]) => {
setCheckedList(list);
};
const onCheckAllChange: CheckboxProps['onChange'] = (e) => {
setCheckedList(e.target.checked ? plainOptions : []);
};
return (
<>
Check all
>
);
};
export default App;
```
### Use with Grid
We can use Checkbox and Grid in Checkbox.Group, to implement complex layout.
```tsx
import React from 'react';
import { Checkbox, Col, Row } from 'antd';
import type { GetProp } from 'antd';
const onChange: GetProp = (checkedValues) => {
console.log('checked = ', checkedValues);
};
const App: React.FC = () => (
A
B
C
D
E
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Checkbox by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Checkbox, Flex } from 'antd';
import type { CheckboxProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
import clsx from 'clsx';
const useStyles = createStyles(({ token, css }) => ({
root: css`
border-radius: ${token.borderRadius}px;
background-color: ${token.colorBgContainer};
`,
icon: css`
border-color: ${token.colorWarning};
`,
label: css`
color: ${token.colorTextDisabled};
font-weight: bold;
`,
iconChecked: css`
background-color: ${token.colorWarning};
`,
labelChecked: css`
color: ${token.colorWarning};
`,
}));
// Object style
const styles: CheckboxProps['styles'] = {
icon: {
borderRadius: 6,
},
label: {
color: 'blue',
},
};
const App: React.FC = () => {
const { styles: classNamesStyles } = useStyles();
// Function classNames - dynamically adjust based on checked state
const classNamesFn: CheckboxProps['classNames'] = (
info,
): GetProp => {
if (info.props.checked) {
return {
root: clsx(classNamesStyles.root),
icon: clsx(classNamesStyles.icon, classNamesStyles.iconChecked),
label: clsx(classNamesStyles.label, classNamesStyles.labelChecked),
};
}
return {
root: classNamesStyles.root,
icon: classNamesStyles.icon,
label: classNamesStyles.label,
};
};
return (
Object styles
Function styles
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
#### Checkbox
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| checked | Specifies whether the checkbox is selected | boolean | false | | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| defaultChecked | Specifies the initial state: whether or not the checkbox is selected | boolean | false | | × |
| disabled | If disable checkbox | boolean | false | | × |
| indeterminate | The indeterminate checked state of checkbox | boolean | false | | × |
| onChange | The callback function that is triggered when the state changes | (e: CheckboxChangeEvent) => void | - | | × |
| onBlur | Called when leaving the component | function() | - | | × |
| onFocus | Called when entering the component | function() | - | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
#### Checkbox.Group
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| defaultValue | Default selected value | (string \| number)\[] | \[] | |
| disabled | If disable all checkboxes | boolean | false | |
| name | The `name` property of all `input[type="checkbox"]` children | string | - | |
| options | Specifies options | string\[] \| number\[] \| Option\[] | \[] | |
| value | Used for setting the currently selected value | (string \| number \| boolean)\[] | \[] | |
| title | title of the option | `string` | - | |
| className | className of the option | `string` | - | 5.25.0 |
| style | styles of the option | `React.CSSProperties` | - | |
| onChange | The callback function that is triggered when the state changes | (checkedValue: T[]) => void | - | |
##### Option
```typescript
interface Option {
label: string;
value: string;
disabled?: boolean;
}
```
### Methods
#### Checkbox
| Name | Description | Version |
| ------------- | ------------------------------------ | ------- |
| blur() | Remove focus | |
| focus() | Get focus | |
| nativeElement | Returns the DOM node of the Checkbox | 5.17.3 |
## Semantic DOM
https://ant.design/components/checkbox/semantic.md
## Design Token
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| colorBgContainer | Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. | string | |
| colorBgContainerDisabled | Control the background color of container in disabled state. | string | |
| colorBorder | Default border color, used to separate different elements, such as: form separator, card separator, etc. | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorPrimaryHover | Hover state under the main color gradient. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDisabled | Control the color of text in disabled state. | string | |
| colorWhite | Pure white color don't changed by theme | string | |
| controlInteractiveSize | Control the interactive size of control component. | number | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeLG | Large font size | number | |
| lineHeight | Line height of text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| lineWidthBold | The default line width of the outline class components, such as Button, Input, Select, etc. | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| motionDurationFast | Motion speed, fast speed. Used for small element animation interaction. | string | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseInBack | Preset motion curve. | string | |
| motionEaseOutBack | Preset motion curve. | string | |
| paddingXS | Control the extra small padding of the element. | number | |
## FAQ
### Why not work in Form.Item? {#faq-form-item-limitations}
Form.Item default bind value to `value` property, but Checkbox value property is `checked`. You can use `valuePropName` to change bind property.
```tsx | pure
```
---
## collapse
Source: https://ant.design/components/collapse.md
---
category: Components
group: Data Display
title: Collapse
description: A content area which can be collapsed and expanded.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*B7HKR5OBe8gAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*sir-TK0HkWcAAAAAAAAAAAAADrJ8AQ/original
---
## When To Use
- Can be used to group or hide complex regions to keep the page clean.
- `Accordion` is a special kind of `Collapse`, which allows only one panel to be expanded at a time.
## Examples
### Collapse
By default, any number of panels can be expanded at a time. The first panel is expanded in this example.
```tsx
import React from 'react';
import type { CollapseProps } from 'antd';
import { Collapse } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header 1',
children: {text}
,
},
{
key: '2',
label: 'This is panel header 2',
children: {text}
,
},
{
key: '3',
label: 'This is panel header 3',
children: {text}
,
},
];
const App: React.FC = () => {
const onChange = (key: string | string[]) => {
console.log(key);
};
return ;
};
export default App;
```
### Size
Ant Design supports a default collapse size as well as a large and small size.
If a large or small collapse is desired, set the `size` property to either `large` or `small` respectively. Omit the `size` property for a collapse with the default `medium` size.
```tsx
import React from 'react';
import { Collapse, Divider } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const App: React.FC = () => (
<>
Medium Size
{text} }]}
/>
Small Size
{text} }]}
/>
Large Size
{text} }]}
/>
>
);
export default App;
```
### Accordion
In accordion mode, only one panel can be expanded at a time.
```tsx
import React from 'react';
import type { CollapseProps } from 'antd';
import { Collapse } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header 1',
children: {text}
,
},
{
key: '2',
label: 'This is panel header 2',
children: {text}
,
},
{
key: '3',
label: 'This is panel header 3',
children: {text}
,
},
];
const App: React.FC = () => ;
export default App;
```
### Nested panel
`Collapse` is nested inside the `Collapse`.
```tsx
import React from 'react';
import type { CollapseProps } from 'antd';
import { Collapse } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const itemsNest: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel nest panel',
children: {text}
,
},
];
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header 1',
children: ,
},
{
key: '2',
label: 'This is panel header 2',
children: {text}
,
},
{
key: '3',
label: 'This is panel header 3',
children: {text}
,
},
];
const App: React.FC = () => {
const onChange = (key: string | string[]) => {
console.log(key);
};
return ;
};
export default App;
```
### Borderless
A borderless style of Collapse.
```tsx
import React from 'react';
import type { CollapseProps } from 'antd';
import { Collapse } from 'antd';
const text = (
A dog is a type of domesticated animal. Known for its loyalty and faithfulness, it can be found
as a welcome guest in many households across the world.
);
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header 1',
children: text,
},
{
key: '2',
label: 'This is panel header 2',
children: text,
},
{
key: '3',
label: 'This is panel header 3',
children: text,
},
];
const App: React.FC = () => ;
export default App;
```
### Custom Panel
Customize the background, border, margin styles and icon for each panel.
```tsx
import type { CSSProperties } from 'react';
import React from 'react';
import { CaretRightOutlined } from '@ant-design/icons';
import type { CollapseProps } from 'antd';
import { Collapse, theme } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const getItems: (panelStyle: CSSProperties) => CollapseProps['items'] = (panelStyle) => [
{
key: '1',
label: 'This is panel header 1',
children: {text}
,
style: panelStyle,
},
{
key: '2',
label: 'This is panel header 2',
children: {text}
,
style: panelStyle,
},
{
key: '3',
label: 'This is panel header 3',
children: {text}
,
style: panelStyle,
},
];
const App: React.FC = () => {
const { token } = theme.useToken();
const panelStyle: React.CSSProperties = {
marginBottom: 24,
background: token.colorFillAlter,
borderRadius: token.borderRadiusLG,
border: 'none',
};
return (
}
style={{ background: token.colorBgContainer }}
items={getItems(panelStyle)}
/>
);
};
export default App;
```
### No arrow
You can hide the arrow icon by passing `showArrow={false}` to `CollapsePanel` component.
```tsx
import React from 'react';
import type { CollapseProps } from 'antd';
import { Collapse } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header with arrow icon',
children: {text}
,
},
{
key: '2',
label: 'This is panel header with no arrow icon',
children: {text}
,
showArrow: false,
},
];
const App: React.FC = () => {
const onChange = (key: string | string[]) => {
console.log(key);
};
return ;
};
export default App;
```
### Extra node
Render extra element in the top-right corner of each panel.
```tsx
import React, { useState } from 'react';
import { SettingOutlined } from '@ant-design/icons';
import type { CollapseProps } from 'antd';
import { Collapse, Select } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const App: React.FC = () => {
const [expandIconPlacement, setExpandIconPlacement] =
useState('start');
const onPlacementChange = (newExpandIconPlacement: CollapseProps['expandIconPlacement']) => {
setExpandIconPlacement(newExpandIconPlacement);
};
const onChange = (key: string | string[]) => {
console.log(key);
};
const genExtra = () => (
{
// If you don't want click extra trigger collapse, you can prevent this:
event.stopPropagation();
}}
/>
);
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header 1',
children: {text}
,
extra: genExtra(),
},
{
key: '2',
label: 'This is panel header 2',
children: {text}
,
extra: genExtra(),
},
{
key: '3',
label: 'This is panel header 3',
children: {text}
,
extra: genExtra(),
},
];
return (
<>
Expand Icon Placement:
>
);
};
export default App;
```
### Ghost Collapse
Making collapse's background to transparent.
```tsx
import React from 'react';
import type { CollapseProps } from 'antd';
import { Collapse } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header 1',
children: {text}
,
},
{
key: '2',
label: 'This is panel header 2',
children: {text}
,
},
{
key: '3',
label: 'This is panel header 3',
children: {text}
,
},
];
const App: React.FC = () => ;
export default App;
```
### Collapsible
Specify the trigger area of collapsible by `collapsible`.
```tsx
import React from 'react';
import { Collapse, Space } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const App: React.FC = () => (
{text},
},
]}
/>
{text},
},
]}
/>
{text},
},
]}
/>
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Collapse by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import type { CollapseProps, GetProp } from 'antd';
import { Collapse, Flex } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
background-color: #fafafa;
border: 1px solid #e0e0e0;
border-radius: 8px;
`,
}));
const element = (
A dog is a type of domesticated animal. Known for its loyalty and faithfulness, it can be found
as a welcome guest in many households across the world.
);
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header 1',
children: element,
},
{
key: '2',
label: 'This is panel header 2',
children: element,
},
{
key: '3',
label: 'This is panel header 3',
children: element,
},
];
const styles: CollapseProps['styles'] = {
root: {
backgroundColor: '#fafafa',
border: '1px solid #e0e0e0',
borderRadius: 8,
},
header: {
backgroundColor: '#f0f0f0',
padding: '12px 16px',
color: '#141414',
},
};
const stylesFn: CollapseProps['styles'] = ({
props,
}): GetProp => {
if (props.size === 'large') {
return {
root: {
backgroundColor: '#fff',
border: '1px solid #696FC7',
borderRadius: 8,
},
header: {
backgroundColor: '#F5EFFF',
padding: '12px 16px',
color: '#141414',
},
};
}
};
const App: React.FC = () => {
const sharedProps: CollapseProps = { classNames, items };
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Collapse
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| accordion | If true, Collapse renders as Accordion | boolean | false | | × |
| activeKey | Key of the active panel | string\[] \| string number\[] \| number | No default value. In [accordion mode](#collapse-demo-accordion), it's the key of the first panel | | × |
| bordered | Toggles rendering of the border around the collapse block | boolean | true | | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| collapsible | Specify how to trigger Collapse. Either by clicking icon or by clicking any area in header or disable collapse functionality itself | `header` \| `icon` \| `disabled` | - | 4.9.0 | × |
| defaultActiveKey | Key of the initial active panel | string\[] \| string number\[] \| number | - | | × |
| ~~destroyInactivePanel~~ | Destroy Inactive Panel | boolean | false | | × |
| destroyOnHidden | Destroy Inactive Panel | boolean | false | 5.25.0 | × |
| expandIcon | Customize the collapse expand icon | (panelProps) => ReactNode | - | | 5.15.0 |
| expandIconPlacement | Set expand icon placement | `start` \| `end` | `start` | - | × |
| ~~expandIconPosition~~ | Set expand icon position, Please use `expandIconPlacement` instead | `start` \| `end` | - | 4.21.0 | × |
| ghost | Make the collapse borderless and its background transparent | boolean | false | 4.4.0 | × |
| size | Set the size of collapse | `large` \| `medium` \| `small` | `medium` | 5.2.0 | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| onChange | Callback function executed when active panel is changed | function | - | | × |
| items | collapse items content | [ItemType](#itemtype) | - | 5.6.0 | × |
### ItemType
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| classNames | Semantic structure className | [`Record`](#semantic-dom) | - | 5.21.0 |
| collapsible | Specify whether the panel be collapsible or the trigger area of collapsible | `header` \| `icon` \| `disabled` | - | |
| children | Body area content | ReactNode | - | |
| extra | The extra element in the corner | ReactNode | - | |
| forceRender | Forced render of content on panel, instead of lazy rendering after clicking on header | boolean | false | |
| key | Unique key identifying the panel from among its siblings | string \| number | - | |
| label | Title of the panel | ReactNode | - | - |
| showArrow | If false, panel will not show arrow icon. If false, collapsible can't be set as icon | boolean | true | |
| styles | Semantic DOM style | [`Record`](#semantic-dom) | - | 5.21.0 |
### Collapse.Panel
:::warning{title=Deprecated}
When using version >= 5.6.0, we prefer to configuring the panel by `items`.
:::
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| collapsible | Specify whether the panel be collapsible or the trigger area of collapsible | `header` \| `icon` \| `disabled` | - | 4.9.0 (icon: 4.24.0) |
| extra | The extra element in the corner | ReactNode | - | |
| forceRender | Forced render of content on panel, instead of lazy rendering after clicking on header | boolean | false | |
| header | Title of the panel | ReactNode | - | |
| key | Unique key identifying the panel from among its siblings | string \| number | - | |
| showArrow | If false, panel will not show arrow icon. If false, collapsible can't be set as icon | boolean | true | |
## Semantic DOM
https://ant.design/components/collapse/semantic.md
## Design Token
## Component Token (Collapse)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderlessContentBg | Background of content in borderless style | string | transparent |
| borderlessContentPadding | Padding of content in borderless style | Padding \| undefined | 4px 16px 16px |
| contentBg | Background of content | string | #ffffff |
| contentPadding | Padding of content | Padding \| undefined | 16px 16px |
| headerBg | Background of header | string | rgba(0,0,0,0.02) |
| headerPadding | Padding of header | Padding \| undefined | 12px 16px |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| colorBorder | Default border color, used to separate different elements, such as: form separator, card separator, etc. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDisabled | Control the color of text in disabled state. | string | |
| colorTextHeading | Control the font color of heading. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeIcon | Control the font size of operation icon in Select, Cascader, etc. Normally same as fontSizeSM. | number | |
| fontSizeLG | Large font size | number | |
| lineHeight | Line height of text. | number | |
| lineHeightLG | Line height of large text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| marginSM | Control the margin of an element, with a medium-small size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseInOut | Preset motion curve. | string | |
| padding | Control the padding of the element. | number | |
| paddingLG | Control the large padding of the element. | number | |
| paddingSM | Control the small padding of the element. | number | |
| paddingXS | Control the extra small padding of the element. | number | |
---
## color-picker
Source: https://ant.design/components/color-picker.md
---
category: Components
title: ColorPicker
description: Used for color selection.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*PpY4RYNM8UcAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*EHL-QYJofZsAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group:
title: Data Entry
---
## When To Use
Used when the user needs to make a customized color selection.
## Examples
### Basic Usage
Basic Usage.
```tsx
import React from 'react';
import { ColorPicker } from 'antd';
const Demo = () => ;
export default Demo;
```
### Trigger size
Ant Design supports three trigger sizes: small, default and large.
If a large or small trigger is desired, set the `size` property to either `large` or `small` respectively. Omit the `size` property for a trigger with the default size.
```tsx
import React from 'react';
import { ColorPicker, Space } from 'antd';
const Demo = () => (
);
export default Demo;
```
### controlled mode
Set the component to controlled mode. Will lock the display color if controlled by `onChangeComplete`.
```tsx
import React, { useState } from 'react';
import { ColorPicker, Space } from 'antd';
import type { ColorPickerProps, GetProp } from 'antd';
type Color = GetProp;
const Demo: React.FC = () => {
const [color, setColor] = useState('#1677ff');
return (
);
};
export default Demo;
```
### Line Gradient
Set the color to a single or a gradient color via `mode`.
```tsx
import React from 'react';
import { ColorPicker, Space } from 'antd';
const DEFAULT_COLOR = [
{
color: 'rgb(16, 142, 233)',
percent: 0,
},
{
color: 'rgb(135, 208, 104)',
percent: 100,
},
];
const Demo = () => (
{
console.log(color.toCssString());
}}
/>
{
console.log(color.toCssString());
}}
/>
);
export default Demo;
```
### Rendering Trigger Text
Renders the default text of the trigger, effective when `showText` is `true`. When customizing text, you can use `showText` as a function to return custom text.
```tsx
import React, { useState } from 'react';
import { DownOutlined } from '@ant-design/icons';
import { ColorPicker, Space } from 'antd';
const Demo = () => {
const [open, setOpen] = useState(false);
return (
Custom Text ({color.toHexString()}) }
/>
(
)}
/>
);
};
export default Demo;
```
### Disable
Set to disabled state.
```tsx
import React from 'react';
import { ColorPicker } from 'antd';
export default () => ;
```
### Disabled Alpha
Disabled color alpha.
```tsx
import React from 'react';
import { ColorPicker } from 'antd';
const Demo = () => ;
export default Demo;
```
### Clear Color
Clear Color.
```tsx
import React from 'react';
import { ColorPicker } from 'antd';
export default () => {
const [color, setColor] = React.useState('#1677ff');
return (
{
setColor(c.toHexString());
}}
/>
);
};
```
### Custom Trigger
Triggers for customizing color panels.
```tsx
import React, { useMemo, useState } from 'react';
import { Button, ColorPicker } from 'antd';
import type { ColorPickerProps, GetProp } from 'antd';
type Color = Extract, string | { cleared: any }>;
const Demo: React.FC = () => {
const [color, setColor] = useState('#1677ff');
const bgColor = useMemo(
() => (typeof color === 'string' ? color : color!.toHexString()),
[color],
);
const btnStyle: React.CSSProperties = {
backgroundColor: bgColor,
};
return (
open
);
};
export default Demo;
```
### Custom Trigger Event
Triggers event for customizing color panels, provide options `click` and `hover`.
```tsx
import React from 'react';
import { ColorPicker } from 'antd';
const Demo = () => ;
export default Demo;
```
### Color Format
Encoding formats, support `HEX`, `HSB`, `RGB`.
```tsx
import React, { useState } from 'react';
import { ColorPicker, Space } from 'antd';
import type { ColorPickerProps, GetProp } from 'antd';
type Color = Extract, string | { cleared: any }>;
type Format = GetProp;
const HexCase: React.FC = () => {
const [colorHex, setColorHex] = useState('#1677ff');
const [formatHex, setFormatHex] = useState('hex');
const hexString = React.useMemo(
() => (typeof colorHex === 'string' ? colorHex : colorHex?.toHexString()),
[colorHex],
);
return (
HEX: {hexString}
);
};
const HsbCase: React.FC = () => {
const [colorHsb, setColorHsb] = useState('hsb(215, 91%, 100%)');
const [formatHsb, setFormatHsb] = useState('hsb');
const hsbString = React.useMemo(
() => (typeof colorHsb === 'string' ? colorHsb : colorHsb?.toHsbString()),
[colorHsb],
);
return (
HSB: {hsbString}
);
};
const RgbCase: React.FC = () => {
const [colorRgb, setColorRgb] = useState('rgb(22, 119, 255)');
const [formatRgb, setFormatRgb] = useState('rgb');
const rgbString = React.useMemo(
() => (typeof colorRgb === 'string' ? colorRgb : colorRgb?.toRgbString()),
[colorRgb],
);
return (
RGB: {rgbString}
);
};
const Demo: React.FC = () => (
);
export default Demo;
```
### Preset Colors
Set the presets color of the color picker.
```tsx
import React from 'react';
import { generate, green, presetPalettes, red } from '@ant-design/colors';
import { ColorPicker, theme } from 'antd';
import type { ColorPickerProps } from 'antd';
type Presets = Required['presets'][number];
function genPresets(presets = presetPalettes) {
return Object.entries(presets).map(([label, colors]) => ({ label, colors, key: label }));
}
const Demo: React.FC = () => {
const { token } = theme.useToken();
const presets = genPresets({ primary: generate(token.colorPrimary), red, green });
return ;
};
export default Demo;
```
### Custom Render Panel
Rendering of the free control panel via `panelRender`.
```tsx
import React from 'react';
import { cyan, generate, green, presetPalettes, red } from '@ant-design/colors';
import { Col, ColorPicker, Divider, Row, Space, theme } from 'antd';
import type { ColorPickerProps } from 'antd';
type Presets = Required['presets'][number];
function genPresets(presets = presetPalettes) {
return Object.entries(presets).map(([label, colors]) => ({ label, colors, key: label }));
}
const HorizontalLayoutDemo = () => {
const { token } = theme.useToken();
const presets = genPresets({
primary: generate(token.colorPrimary),
red,
green,
cyan,
});
const customPanelRender: ColorPickerProps['panelRender'] = (
_,
{ components: { Picker, Presets } },
) => (
);
return (
);
};
const BasicDemo = () => (
(
)}
/>
);
export default () => (
Add title:
Horizontal layout:
);
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of ColorPicker by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { ColorPicker, Flex, Space } from 'antd';
import type { ColorPickerProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
root: {
borderRadius: token.borderRadius,
},
}));
const stylesObject: ColorPickerProps['styles'] = {
popup: {
root: {
border: '1px solid #fff',
},
},
};
const stylesFn: ColorPickerProps['styles'] = (
info,
): GetProp => {
if (info.props.size === 'large') {
return {
popup: {
root: {
border: '1px solid #722ed1',
},
},
};
}
return {};
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
> This component is available since `antd@5.5.0`.
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| :-- | :-- | :-- | :-- | :-- | --- |
| allowClear | Allow clearing color selected | boolean | false | | × |
| arrow | Configuration for popup arrow | `boolean \| { pointAtCenter: boolean }` | true | | 6.3.0 |
| children | Trigger of ColorPicker | React.ReactNode | - | | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| defaultValue | Default value of color | [ColorType](#colortype) | - | | × |
| defaultFormat | Default format of color | `rgb` \| `hex` \| `hsb` | `hex` | 5.9.0 | × |
| disabled | Disable ColorPicker | boolean | - | | × |
| disabledAlpha | Disable Alpha | boolean | - | 5.8.0 | × |
| disabledFormat | Disable format of color | boolean | - | 5.22.0 | × |
| ~~destroyTooltipOnHide~~ | Whether destroy dom when close | `boolean` | false | 5.7.0 | × |
| destroyOnHidden | Whether destroy dom when close | `boolean` | false | 5.25.0 | × |
| format | Format of color | `rgb` \| `hex` \| `hsb` | - | | × |
| mode | Configure single or gradient color | `'single' \| 'gradient' \| ('single' \| 'gradient')[]` | `single` | 5.20.0 | × |
| open | Whether to show popup | boolean | - | | × |
| presets | Preset colors | [PresetColorType](#presetcolortype) | - | | × |
| placement | Placement of popup | The design of the [placement](/components/tooltip/#api) parameter is the same as the `Tooltips` component. | `bottomLeft` | | × |
| panelRender | Custom Render Panel | `(panel: React.ReactNode, extra: { components: { Picker: FC; Presets: FC } }) => React.ReactNode` | - | 5.7.0 | × |
| showText | Show color text | boolean \| `(color: Color) => React.ReactNode` | - | 5.7.0 | × |
| size | Setting the trigger size | `large` \| `medium` \| `small` | `medium` | 5.7.0 | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| trigger | ColorPicker trigger mode | `hover` \| `click` | `click` | | × |
| value | Value of color | [ColorType](#colortype) | - | | × |
| onChange | Callback when `value` is changed | `(value: Color, css: string) => void` | - | | × |
| onChangeComplete | Called when color pick ends. Will not change the display color when `value` controlled by `onChangeComplete` | `(value: Color) => void` | - | 5.7.0 | × |
| onFormatChange | Callback when `format` is changed | `(format: 'hex' \| 'rgb' \| 'hsb') => void` | - | | × |
| onOpenChange | Callback when `open` is changed | `(open: boolean) => void` | - | | × |
| onClear | Called when clear | `() => void` | - | 5.6.0 | × |
#### ColorType
```typescript
type ColorType =
| string
| Color
| {
color: string;
percent: number;
}[];
```
#### PresetColorType
```typescript
type PresetColorType = {
label: React.ReactNode;
defaultOpen?: boolean;
key?: React.Key;
colors: ColorType[];
};
```
### Color
| Property | Description | Type | Version |
| :-- | :-- | :-- | :-- |
| toCssString | Convert to CSS support format | `() => string` | 5.20.0 |
| toHex | Convert to `hex` format characters, the return type like: `1677ff` | `() => string` | - |
| toHexString | Convert to `hex` format color string, the return type like: `#1677ff` | `() => string` | - |
| toHsb | Convert to `hsb` object | `() => ({ h: number, s: number, b: number, a: number })` | - |
| toHsbString | Convert to `hsb` format color string, the return type like: `hsb(215, 91%, 100%)` | `() => string` | - |
| toRgb | Convert to `rgb` object | `() => ({ r: number, g: number, b: number, a: number })` | - |
| toRgbString | Convert to `rgb` format color string, the return type like: `rgb(22, 119, 255)` | `() => string` | - |
## Semantic DOM
https://ant.design/components/color-picker/semantic.md
## FAQ
### Questions about color assignment {#faq-color-assignment}
The value of the color selector supports both string color values and selector-generated `Color` objects. However, since there is a precision error when converting color strings of different formats to each other, it is recommended to use selector-generated `Color` objects for assignment operations in controlled scenarios, so that the precision problem can be avoided and the values are guaranteed to be accurate and the selector can work as expected.
---
## config-provider
Source: https://ant.design/components/config-provider.md
---
category: Components
group: Other
title: ConfigProvider
description: Provide a uniform configuration support for components.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*NVKORa7BCVwAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*YC4ERpGAddoAAAAAAAAAAAAADrJ8AQ/original
---
## Usage
This component provides a configuration to all React components underneath itself via the [context API](https://react.dev/learn/passing-data-deeply-with-context). In the render tree all components will have access to the provided config.
```tsx
import React from 'react';
import { ConfigProvider } from 'antd';
// ...
const Demo: React.FC = () => (
);
export default Demo;
```
### Content Security Policy {#csp}
Some components use dynamic style to support wave effect. You can config `csp` prop if Content Security Policy (CSP) is enabled:
```tsx
My Button
```
## Examples
### Locale
Components which need localization support are listed here, you can toggle the language in the demo.
```tsx
import React, { useState } from 'react';
import { EllipsisOutlined } from '@ant-design/icons';
import type {
ConfigProviderProps,
RadioChangeEvent,
TableProps,
TourProps,
UploadFile,
} from 'antd';
import {
Button,
Calendar,
ConfigProvider,
DatePicker,
Divider,
Form,
Image,
Input,
InputNumber,
Modal,
Pagination,
Popconfirm,
QRCode,
Radio,
Select,
Space,
Table,
theme,
TimePicker,
Tour,
Transfer,
Upload,
} from 'antd';
import enUS from 'antd/locale/en_US';
import zhCN from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
type Locale = ConfigProviderProps['locale'];
dayjs.locale('en');
const { RangePicker } = DatePicker;
const columns: TableProps['columns'] = [
{
title: 'Name',
dataIndex: 'name',
filters: [{ text: 'filter1', value: 'filter1' }],
},
{
title: 'Age',
dataIndex: 'age',
},
];
const Page: React.FC = () => {
const { token } = theme.useToken();
const [open, setOpen] = useState(false);
const [tourOpen, setTourOpen] = useState(false);
const tourRefs = React.useRef([]);
const showModal = () => {
setOpen(true);
};
const hideModal = () => {
setOpen(false);
};
const info = () => {
Modal.info({
title: 'some info',
content: 'some info',
});
};
const confirm = () => {
Modal.confirm({
title: 'some info',
content: 'some info',
});
};
const steps: TourProps['steps'] = [
{
title: 'Upload File',
description: 'Put your files here.',
target: () => tourRefs.current[0],
},
{
title: 'Save',
description: 'Save your changes.',
target: () => tourRefs.current[1],
},
{
title: 'Other Actions',
description: 'Click to see other actions.',
target: () => tourRefs.current[2],
},
];
const fileList: UploadFile[] = [
{
uid: '-1',
name: 'image.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
{
uid: '-2',
percent: 50,
name: 'image.png',
status: 'uploading',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
{
uid: '-3',
name: 'image.png',
status: 'error',
},
];
return (
Show Modal
Show info
Show confirm
Click to confirm
Submit
Locale Modal
console.log('refresh')}
/>
Tour
setTourOpen(true)}>
Begin Tour
{
node && tourRefs.current.splice(0, 0, node);
}}
>
{' '}
Upload
{
node && tourRefs.current.splice(1, 0, node);
}}
type="primary"
>
Save
{
node && tourRefs.current.splice(2, 0, node);
}}
icon={ }
/>
setTourOpen(false)} />
);
};
const App: React.FC = () => {
const [locale, setLocale] = useState(enUS);
const changeLocale = (e: RadioChangeEvent) => {
const localeValue = e.target.value;
setLocale(localeValue);
if (!localeValue) {
dayjs.locale('en');
} else {
dayjs.locale('zh-cn');
}
};
return (
<>
Change locale of components:
English
中文
>
);
};
export default App;
```
### Direction
Components which support rtl direction are listed here, you can toggle the direction in the demo.
```css
.head-example {
display: inline-block;
width: 42px;
height: 42px;
vertical-align: middle;
background: #eee;
border-radius: 4px;
}
```
```tsx
import React, { useState } from 'react';
import {
DownloadOutlined,
LeftOutlined,
MinusOutlined,
PlusOutlined,
RightOutlined,
SearchOutlined as SearchIcon,
SmileOutlined,
} from '@ant-design/icons';
import type { ConfigProviderProps, RadioChangeEvent } from 'antd';
import {
Badge,
Button,
Cascader,
Col,
ConfigProvider,
Divider,
Flex,
Input,
InputNumber,
Modal,
Pagination,
Radio,
Rate,
Row,
Select,
Space,
Steps,
Switch,
Tree,
TreeSelect,
} from 'antd';
type DirectionType = ConfigProviderProps['direction'];
const { Search } = Input;
const treeData = [
{
title: 'parent 1',
key: '0-0',
children: [
{
title: 'parent 1-0',
key: '0-0-0',
disabled: true,
children: [
{ title: 'leaf', key: '0-0-0-0', disableCheckbox: true },
{ title: 'leaf', key: '0-0-0-1' },
],
},
{
title: 'parent 1-1',
key: '0-0-1',
children: [{ title: sss , key: '0-0-1-0' }],
},
],
},
];
const treeSelectData = [
{
title: 'parent 1',
value: '0-1',
children: [
{
title: 'parent 1-0',
value: '0-1-1',
children: [
{ title: 'my leaf', value: 'random' },
{ title: 'your leaf', value: 'random1' },
],
},
{
title: 'parent 1-1',
value: 'random2',
children: [{ title: sss , value: 'random3' }],
},
],
},
];
const cascaderOptions = [
{
value: 'tehran',
label: 'تهران',
children: [
{
value: 'tehran-c',
label: 'تهران',
children: [
{
value: 'saadat-abad',
label: 'سعادت آباد',
},
],
},
],
},
{
value: 'ardabil',
label: 'اردبیل',
children: [
{
value: 'ardabil-c',
label: 'اردبیل',
children: [
{
value: 'pirmadar',
label: 'پیرمادر',
},
],
},
],
},
{
value: 'gilan',
label: 'گیلان',
children: [
{
value: 'rasht',
label: 'رشت',
children: [
{
value: 'district-3',
label: 'منطقه ۳',
},
],
},
],
},
];
type Placement = 'bottomLeft' | 'bottomRight' | 'topLeft' | 'topRight';
const Page: React.FC<{ placement: Placement }> = ({ placement }) => {
const [currentStep, setCurrentStep] = useState(0);
const [modalOpen, setModalOpen] = useState(false);
const [badgeCount, setBadgeCount] = useState(5);
const [showBadge, setShowBadge] = useState(true);
const selectBefore = (
);
const selectAfter = (
);
// ==== Cascader ====
const cascaderFilter = (inputValue: string, path: { label: string }[]) =>
path.some((option) => option.label.toLowerCase().includes(inputValue.toLowerCase()));
const onCascaderChange = (value: any) => {
console.log(value);
};
// ==== End Cascader ====
// ==== Modal ====
const showModal = () => {
setModalOpen(true);
};
const handleOk = () => {
setModalOpen(false);
};
const handleCancel = () => {
setModalOpen(false);
};
// ==== End Modal ====
const onStepsChange = (newCurrentStep: number) => {
console.log('onChange:', newCurrentStep);
setCurrentStep(newCurrentStep);
};
// ==== Badge ====
const increaseBadge = () => {
setBadgeCount(badgeCount + 1);
};
const declineBadge = () => {
setBadgeCount((prev) => (prev - 1 < 0 ? 0 : prev - 1));
};
const onChangeBadge = (checked: boolean) => {
setShowBadge(checked);
};
// ==== End Badge ====
return (
Cascader example
}
options={cascaderOptions}
onChange={onCascaderChange}
placeholder="یک مورد انتخاب کنید"
placement={placement}
/>
With search:
}
options={cascaderOptions}
onChange={onCascaderChange}
placeholder="Select an item"
placement={placement}
showSearch={{ filter: cascaderFilter }}
/>
Switch example
Radio Group example
تهران
اصفهان
فارس
خوزستان
Button example
} />
} />
} />
}>
Download
}>
Download
}>
Backward
} iconPlacement="end">
Forward
Loading
Loading
Tree example
Input (Input Group) example
{selectBefore}
{selectAfter}
Select example
TreeSelect example
Modal example
Open Modal
نگاشتههای خود را اینجا قراردهید
نگاشتههای خود را اینجا قراردهید
نگاشتههای خود را اینجا قراردهید
Steps example
Rate example
* Note: Half star not implemented in RTL direction, it will be
supported after{' '}
rc-rate
{' '}
implement rtl support.
Badge example
} onClick={declineBadge} />
} onClick={increaseBadge} />
Pagination example
Grid System example
* Note: Every calculation in RTL grid system is from right side
(offset, push, etc.)
col-8
col-8
col-6 col-offset-6
col-6 col-offset-6
col-12 col-offset-6
col-18 col-push-6
col-6 col-pull-18
);
};
const App: React.FC = () => {
const [direction, setDirection] = useState('ltr');
const [placement, setPlacement] = useState('bottomLeft');
const changeDirection = (e: RadioChangeEvent) => {
const directionValue = e.target.value;
setDirection(directionValue);
setPlacement(directionValue === 'rtl' ? 'bottomRight' : 'bottomLeft');
};
return (
<>
Change direction of components:
LTR
RTL
>
);
};
export default App;
```
### Component size
Config component default size.
```tsx
import React, { useState } from 'react';
import {
Button,
Card,
ConfigProvider,
DatePicker,
Divider,
Input,
Radio,
Select,
Space,
Table,
Tabs,
} from 'antd';
import type { ConfigProviderProps } from 'antd';
type SizeType = ConfigProviderProps['componentSize'];
const App: React.FC = () => {
const [componentSize, setComponentSize] = useState('small');
return (
<>
{
setComponentSize(e.target.value);
}}
>
Small
Medium
Large
Button
>
);
};
export default App;
```
### Theme
Modify theme by `theme` prop.
```tsx
import React from 'react';
import {
Button,
ColorPicker,
ConfigProvider,
Divider,
Form,
Input,
InputNumber,
Space,
Switch,
} from 'antd';
import type { ColorPickerProps, GetProp } from 'antd';
type Color = Extract, { cleared: any }>;
type ThemeData = {
borderRadius: number;
colorPrimary: string;
Button?: {
colorPrimary: string;
algorithm?: boolean;
};
};
const defaultData: ThemeData = {
borderRadius: 6,
colorPrimary: '#1677ff',
Button: {
colorPrimary: '#00B96B',
},
};
export default () => {
const [form] = Form.useForm();
const [data, setData] = React.useState(defaultData);
return (
);
};
```
### Custom Wave
Wave effect brings dynamic. Use `component` to determine which component use it. You can also use HappyProvider from [`@ant-design/happy-work-theme`](https://github.com/ant-design/happy-work-theme) to implement dynamic wave effect.
```tsx
import React from 'react';
import { HappyProvider } from '@ant-design/happy-work-theme';
import { Button, ConfigProvider, Flex } from 'antd';
import type { ConfigProviderProps, GetProp } from 'antd';
type WaveConfig = GetProp;
// Prepare effect holder
const createHolder = (node: HTMLElement) => {
const { borderWidth } = getComputedStyle(node);
const borderWidthNum = Number.parseInt(borderWidth, 10);
const div = document.createElement('div');
div.style.position = 'absolute';
div.style.inset = `-${borderWidthNum}px`;
div.style.borderRadius = 'inherit';
div.style.background = 'transparent';
div.style.zIndex = '999';
div.style.pointerEvents = 'none';
div.style.overflow = 'hidden';
node.appendChild(div);
return div;
};
const createDot = (holder: HTMLElement, color: string, left: number, top: number, size = 0) => {
const dot = document.createElement('div');
dot.style.position = 'absolute';
dot.style.insetInlineStart = `${left}px`;
dot.style.top = `${top}px`;
dot.style.width = `${size}px`;
dot.style.height = `${size}px`;
dot.style.borderRadius = '50%';
dot.style.background = color;
dot.style.transform = 'translate3d(-50%, -50%, 0)';
dot.style.transition = 'all 1s ease-out';
holder.appendChild(dot);
return dot;
};
// Inset Effect
const showInsetEffect: WaveConfig['showEffect'] = (node, { event, component }) => {
if (component !== 'Button') {
return;
}
const holder = createHolder(node);
const rect = holder.getBoundingClientRect();
const left = event.clientX - rect.left;
const top = event.clientY - rect.top;
const dot = createDot(holder, 'rgba(255, 255, 255, 0.65)', left, top);
// Motion
requestAnimationFrame(() => {
dot.ontransitionend = () => {
holder.remove();
};
dot.style.width = '200px';
dot.style.height = '200px';
dot.style.opacity = '0';
});
};
// Shake Effect
const showShakeEffect: WaveConfig['showEffect'] = (node, { component }) => {
if (component !== 'Button') {
return;
}
const seq = [0, -15, 15, -5, 5, 0];
const itv = 10;
let steps = 0;
const loop = () => {
cancelAnimationFrame((node as any).effectTimeout);
(node as any).effectTimeout = requestAnimationFrame(() => {
const currentStep = Math.floor(steps / itv);
const current = seq[currentStep];
const next = seq[currentStep + 1];
if (next === undefined || next === null) {
node.style.transform = '';
node.style.transition = '';
return;
}
// Trans from current to next by itv
const angle = current + ((next - current) / itv) * (steps % itv);
node.style.transform = `rotate(${angle}deg)`;
node.style.transition = 'none';
steps += 1;
loop();
});
};
loop();
};
// Component
const Wrapper: React.FC = ({ name, ...wave }) => (
{name}
);
const Demo: React.FC = () => (
Happy Work
);
export default Demo;
```
### Static function
Use `holderRender` to set the `Provider` for the static methods `message`,`modal`,`notification`.
```tsx
import React, { useContext, useLayoutEffect } from 'react';
import { StyleProvider } from '@ant-design/cssinjs';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { App, Button, ConfigProvider, message, Modal, notification, Space } from 'antd';
const Demo: React.FC = () => {
const { locale, theme } = useContext(ConfigProvider.ConfigContext);
useLayoutEffect(() => {
ConfigProvider.config({
holderRender: (children) => (
{children}
),
});
}, [locale, theme]);
return (
{
message.info('This is a normal message');
}}
>
message
{
notification.open({
title: 'Notification Title',
description:
'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
});
}}
>
notification
{
Modal.confirm({
title: 'Do you want to delete these items?',
icon: ,
content: 'Some descriptions',
});
}}
>
Modal
);
};
export default Demo;
```
## API
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| componentDisabled | Config antd component `disabled` | boolean | - | 4.21.0 |
| componentSize | Config antd component size | `small` \| `medium` \| `large` | - | |
| csp | Set [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) config | { nonce: string } | - | |
| direction | Set direction of layout. See [demo](#config-provider-demo-direction) | `ltr` \| `rtl` | `ltr` | |
| getPopupContainer | To set the container of the popup element. The default is to create a `div` element in `body` | `(trigger?: HTMLElement) => HTMLElement \| ShadowRoot` | () => document.body | |
| getTargetContainer | Config Affix, Anchor scroll target container | `() => HTMLElement \| Window \| ShadowRoot` | () => window | 4.2.0 |
| iconPrefixCls | Set icon prefix className | string | `anticon` | 4.11.0 |
| locale | Language package setting, you can find the packages in [antd/locale](https://unpkg.com/antd/locale/) | object | - | |
| popupMatchSelectWidth | Determine whether the dropdown menu and the select input are the same width. Default set `min-width` same as input. Will ignore when value less than select width. `false` will disable virtual scroll | boolean \| number | - | 5.5.0 |
| popupOverflow | Select like component popup logic. Can set to show in viewport or follow window scroll | 'viewport' \| 'scroll' | 'viewport' | 5.5.0 |
| prefixCls | Set prefix className | string | `ant` | |
| renderEmpty | Set empty content of components. Ref [Empty](/components/empty/) | function(componentName: string): ReactNode | - | |
| theme | Set theme, ref [Customize Theme](/docs/react/customize-theme) | [Theme](/docs/react/customize-theme#theme) | - | 5.0.0 |
| variant | Set variant of data entry components | `outlined` \| `filled` \| `borderless` | - | 5.19.0 |
| virtual | Disable virtual scroll when set to `false` | boolean | - | 4.3.0 |
| warning | Config warning level, when `strict` is `false`, it will aggregate deprecated information into a single message | { strict: boolean } | - | 5.10.0 |
| ~~autoInsertSpaceInButton~~ | Button auto spacing config, please use `button={{ autoInsertSpace: boolean }}` instead | boolean | - | - |
| ~~dropdownMatchSelectWidth~~ | Determine whether the dropdown menu and the select input are the same width, please use `popupMatchSelectWidth` instead | boolean | - | - |
### ConfigProvider.config() {#config}
Setting `Modal`, `Message`, `Notification` static config. Does not work on hooks.
```tsx
ConfigProvider.config({
// 5.13.0+
holderRender: (children) => (
{children}
),
});
```
### ConfigProvider.useConfig() 5.3.0+ {#useconfig}
Get the value of the parent `Provider`, Such as `DisabledContextProvider`, `SizeContextProvider`.
```jsx
const {
componentDisabled, // 5.3.0+
componentSize, // 5.3.0+
} = ConfigProvider.useConfig();
```
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| componentDisabled | antd component disabled state | boolean | - | 5.3.0 |
| componentSize | antd component size state | `small` \| `medium` \| `large` | - | 5.3.0 |
### Component Config
The following config keys set common props for corresponding components or global effects. See the related APIs for details:
- `affix`: [Affix](/components/affix#api) (supported since 6.0.0)
- `alert`: [Alert](/components/alert#api) (supported since 5.7.0)
- `anchor`: [Anchor](/components/anchor#api) (supported since 6.0.0)
- `app`: [App](/components/app#api) (supported since 6.3.0)
- `avatar`: [Avatar](/components/avatar#api) (supported since 5.7.0)
- `badge`: [Badge](/components/badge#api) (supported since 5.7.0)
- `borderBeam`: [BorderBeam](/components/border-beam#api) (supported since 6.4.0)
- `breadcrumb`: [Breadcrumb](/components/breadcrumb#api) (supported since 5.7.0)
- `button`: [Button](/components/button#api) (supported since 5.6.0)
- `card`: [Card](/components/card#api) (supported since 5.14.0)
- `cardMeta`: [Card.Meta](/components/card#cardmeta) (supported since 6.0.0)
- `calendar`: [Calendar](/components/calendar#api) (supported since 6.0.0)
- `carousel`: [Carousel](/components/carousel#api) (supported since 5.7.0)
- `cascader`: [Cascader](/components/cascader#api) (supported since 5.13.0)
- `checkbox`: [Checkbox](/components/checkbox#api) (supported since 6.0.0)
- `collapse`: [Collapse](/components/collapse#api) (supported since 5.15.0)
- `colorPicker`: [ColorPicker](/components/color-picker#api) (supported since 6.3.0)
- `datePicker`: [DatePicker](/components/date-picker#api) (supported since 5.7.0)
- `rangePicker`: [RangePicker](/components/date-picker#rangepicker) (supported since 5.11.0)
- `descriptions`: [Descriptions](/components/descriptions#api) (supported since 5.23.0)
- `divider`: [Divider](/components/divider#api) (supported since 5.10.0)
- `drawer`: [Drawer](/components/drawer#api) (supported since 5.10.0)
- `dropdown`: [Dropdown](/components/dropdown#api) (supported since 5.11.0)
- `empty`: [Empty](/components/empty#api) (supported since 5.23.0)
- `flex`: [Flex](/components/flex#api) (supported since 5.10.0)
- `floatButton`: [FloatButton](/components/float-button#api) (supported since 6.0.0)
- `floatButtonGroup`: [FloatButton.Group](/components/float-button#floatbuttongroup) (supported since 5.16.0)
- `form`: [Form](/components/form#api) (supported since 4.8.0)
- `image`: [Image](/components/image#api) (supported since 5.14.0)
- `input`: [Input](/components/input#input) (supported since 4.2.0)
- `inputNumber`: [InputNumber](/components/input-number#api) (supported since 5.19.0)
- `otp`: [Input.OTP](/components/input#inputotp) (supported since 6.0.0)
- `inputPassword`: [Input.Password](/components/input#inputpassword) (supported since 6.4.0)
- `inputSearch`: [Input.Search](/components/input#inputsearch) (supported since 6.4.0)
- `textArea`: [Input.TextArea](/components/input#inputtextarea) (supported since 5.15.0)
- `layout`: [Layout](/components/layout#api) (supported since 5.7.0)
- `list`: [List](/components/list#api) (supported since 5.7.0)
- `masonry`: [Masonry](/components/masonry#api) (supported since 6.0.0)
- `menu`: [Menu](/components/menu#api) (supported since 5.15.0)
- `mentions`: [Mentions](/components/mentions#api) (supported since 5.13.0)
- `message`: [Message](/components/message#api) (supported since 5.7.0)
- `modal`: [Modal](/components/modal#api) (supported since 5.10.0)
- `notification`: [Notification](/components/notification#api) (supported since 5.14.0)
- `pagination`: [Pagination](/components/pagination#api) (supported since 6.0.0)
- `progress`: [Progress](/components/progress#api) (supported since 5.7.0)
- `radio`: [Radio](/components/radio#api) (supported since 6.0.0)
- `rate`: [Rate](/components/rate#api) (supported since 5.7.0)
- `result`: [Result](/components/result#api) (supported since 6.0.0)
- `ribbon`: [Badge.Ribbon](/components/badge#badgeribbon) (supported since 6.0.0)
- `skeleton`: [Skeleton](/components/skeleton#api) (supported since 6.0.0)
- `segmented`: [Segmented](/components/segmented#api) (supported since 6.0.0)
- `select`: [Select](/components/select#api) (supported since 5.13.0)
- `slider`: [Slider](/components/slider#api) (supported since 5.23.0)
- `switch`: [Switch](/components/switch#api) (supported since 6.0.0)
- `space`: [Space](/components/space#api) (supported since 5.6.0)
- `splitter`: [Splitter](/components/splitter#api) (supported since 5.21.0)
- `spin`: [Spin](/components/spin#api) (supported since 5.20.0)
- `statistic`: [Statistic](/components/statistic#api) (supported since 6.0.0)
- `steps`: [Steps](/components/steps#api) (supported since 5.10.0)
- `table`: [Table](/components/table#api) (supported since 6.2.0)
- `tabs`: [Tabs](/components/tabs#api) (supported since 5.14.0)
- `tag`: [Tag](/components/tag#api) (supported since 5.14.0)
- `timeline`: [Timeline](/components/timeline#api) (supported since 6.0.0)
- `timePicker`: [TimePicker](/components/time-picker#api) (supported since 5.13.0)
- `tour`: [Tour](/components/tour#api) (supported since 5.14.0)
- `tooltip`: [Tooltip](/components/tooltip#api) (supported since 6.1.0)
- `popover`: [Popover](/components/popover#api) (supported since 5.23.0)
- `popconfirm`: [Popconfirm](/components/popconfirm#api) (supported since 5.23.0)
- `qrcode`: [QRCode](/components/qr-code#api) (supported since 6.0.0)
- `transfer`: [Transfer](/components/transfer#api) (supported since 5.7.0)
- `tree`: [Tree](/components/tree#api) (supported since 6.0.0)
- `treeSelect`: [TreeSelect](/components/tree-select#api) (supported since 5.19.0)
- `typography`: [Typography](/components/typography#api) (supported since 6.4.0)
- `upload`: [Upload](/components/upload#api) (supported since 5.27.0)
- `watermark`: [Watermark](/components/watermark#api) (supported since 6.0.0)
- `wave`: [WaveConfig](#waveconfig) (supported since 5.8.0)
### WaveConfig
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| disabled | Whether to disable wave effect | boolean | false | |
| showEffect | Customized wave effect | (node: HTMLElement, info: { className, token, component }) => void | - | |
| triggerType | The event that triggers wave effect | `click` \| `pointerdown` \| `pointerup` \| `mousedown` \| `mouseup` | `click` | 6.4.0 |
## FAQ
### How to contribute a new language? {#faq-add-locale}
See [<Adding new language>](/docs/react/i18n#adding-newplanguage).
### Date-related components locale is not working? {#faq-locale-not-work}
See FAQ [Date-related-components-locale-is-not-working?](/docs/react/faq#date-related-components-locale-is-not-working)
### Modal throw error when setting `getPopupContainer`? {#faq-get-popup-container}
Related issue:
When you config `getPopupContainer` to parentNode globally, Modal will throw error of `triggerNode is undefined` because it did not have a triggerNode. You can try the [fix](https://github.com/afc163/feedback-antd/commit/3e4d1ad1bc1a38460dc3bf3c56517f737fe7d44a) below.
```diff
triggerNode.parentNode}
+ getPopupContainer={node => {
+ if (node) {
+ return node.parentNode;
+ }
+ return document.body;
+ }}
>
```
### Why can't ConfigProvider props (like `prefixCls` and `theme`) affect ReactNode inside `message.info`, `notification.open`, `Modal.confirm`? {#faq-message-inherit}
antd will dynamic create React instance by `ReactDOM.render` when call message methods. Whose context is different with origin code located context. We recommend `useMessage`, `useNotification` and `useModal` which , the methods came from `message/notification/Modal` has been deprecated in 5.x.
### Locale is not working with Vite in production mode? {#faq-vite-locale-not-work}
Related issue: [#39045](https://github.com/ant-design/ant-design/issues/39045)
In production mode of Vite, default exports from cjs file should be used like this: `enUS.default`. So you can directly import locale from `es/` directory like `import enUS from 'antd/es/locale/en_US'` to make dev and production have the same behavior.
### `prefixCls` priority(The former is covered by the latter) {#faq-prefixcls-priority}
1. `ConfigProvider.config({ prefixCls: 'prefix-1' })`
2. `ConfigProvider.config({ holderRender: (children) => {children} })`
3. `message.config({ prefixCls: 'prefix-3' })`
---
## date-picker
Source: https://ant.design/components/date-picker.md
---
category: Components
group: Data Entry
title: DatePicker
description: To select or input a date.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*qK9mRqFnBbAAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*wz1QTJSQgmAAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
By clicking the input box, you can select a date from a popup calendar.
## Examples
### Basic
Basic use case. Users can select or input a date in a panel.
```tsx
import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Flex } from 'antd';
const onChange: DatePickerProps['onChange'] = (date, dateString) => {
console.log(date, dateString);
};
const Demo: React.FC = () => (
);
export default Demo;
```
### Range Picker
Set range picker type by `picker` prop.
```tsx
import React from 'react';
import { DatePicker, Space } from 'antd';
const { RangePicker } = DatePicker;
const App: React.FC = () => (
{
console.log('Focus:', info.range);
}}
onBlur={(_, info) => {
console.log('Blur:', info.range);
}}
/>
);
export default App;
```
### Multiple
Multiple selections. Does not support `showTime` and `picker="time"`.
```tsx
import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Flex } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
const onChange: DatePickerProps['onChange'] = (date, dateString) => {
console.log(date, dateString);
};
const defaultValue = [dayjs('2000-01-01'), dayjs('2000-01-03'), dayjs('2000-01-05')];
const App: React.FC = () => (
);
export default App;
```
### Need Confirm
DatePicker will automatically determine whether to show a confirm button according to the `picker` property. You can also set the `needConfirm` property to determine whether to show a confirm button. When `needConfirm` is set, the user must click the confirm button to complete the selection. Otherwise, the selection will be submitted when the picker loses focus or selects a date.
```tsx
import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker } from 'antd';
import type { Dayjs } from 'dayjs';
const onChange: DatePickerProps['onChange'] = (date, dateString) => {
console.log(date, dateString);
};
const App: React.FC = () => ;
export default App;
```
### Switchable picker
Switch in different types of pickers by Select.
```tsx
import React, { useState } from 'react';
import type { DatePickerProps, TimePickerProps } from 'antd';
import { DatePicker, Select, Space, TimePicker } from 'antd';
import type { Dayjs } from 'dayjs';
type PickerType = 'time' | 'date';
interface PickerWithTypeProps {
type: PickerType;
onChange: TimePickerProps['onChange'] | DatePickerProps['onChange'];
}
const PickerWithType: React.FC = ({ type, onChange }) => {
if (type === 'time') {
return ;
}
if (type === 'date') {
return ;
}
return ;
};
const App: React.FC = () => {
const [type, setType] = useState('time');
return (
console.log(value)} />
);
};
export default App;
```
### Date Format
We can set the date format by `format`. When `format` is an array, the input box can be entered in any of the valid formats of the array.
```tsx
import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Space } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
dayjs.extend(customParseFormat);
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const weekFormat = 'MM/DD';
const monthFormat = 'YYYY/MM';
/** Manually entering any of the following formats will perform date parsing */
const dateFormatList = ['DD/MM/YYYY', 'DD/MM/YY', 'DD-MM-YYYY', 'DD-MM-YY'];
const customFormat: DatePickerProps['format'] = (value) =>
`custom format: ${value.format(dateFormat)}`;
const customWeekStartEndFormat: DatePickerProps['format'] = (value) =>
`${dayjs(value).startOf('week').format(weekFormat)} ~ ${dayjs(value)
.endOf('week')
.format(weekFormat)}`;
const App: React.FC = () => (
);
export default App;
```
### Choose Time
This property provides an additional time selection. When `showTime` is an Object, its properties will be passed on to the built-in `TimePicker`.
```tsx
import React from 'react';
import { DatePicker, Space } from 'antd';
import type { DatePickerProps, GetProps } from 'antd';
type RangePickerProps = GetProps;
const { RangePicker } = DatePicker;
const onOk = (value: DatePickerProps['value'] | RangePickerProps['value']) => {
console.log('onOk: ', value);
};
const App: React.FC = () => (
{
console.log('Selected Time: ', value);
console.log('Formatted Selected Time: ', dateString);
}}
onOk={onOk}
/>
{
console.log('Selected Time: ', value);
console.log('Formatted Selected Time: ', dateString);
}}
onOk={onOk}
/>
);
export default App;
```
### Mask Format
Align the date format. Switch the selection by arrow keys. Will try to align the date to the last valid date when blur.
```tsx
import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Space } from 'antd';
const onChange: DatePickerProps['onChange'] = (date, dateString) => {
console.log(date, dateString);
};
const App: React.FC = () => (
);
export default App;
```
### Limit Date Range
Limit the range of available dates by using `minDate` and `maxDate`.
```tsx
import React from 'react';
import { DatePicker } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
dayjs.extend(customParseFormat);
const dateFormat = 'YYYY-MM-DD';
const App: React.FC = () => (
);
export default App;
```
### Disabled
A disabled state of the `DatePicker`. You can also set as array to disable one of input.
```tsx
import React from 'react';
import { DatePicker, Space } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
dayjs.extend(customParseFormat);
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
const App: React.FC = () => (
);
export default App;
```
### Disabled Date & Time
Disable specific dates and times by using `disabledDate` and `disabledTime` respectively, and `disabledTime` only works with `showTime`.
```tsx
import React from 'react';
import { DatePicker, Space } from 'antd';
import type { GetProps } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
type RangePickerProps = GetProps;
dayjs.extend(customParseFormat);
const { RangePicker } = DatePicker;
const range = (start: number, end: number) => {
const result: number[] = [];
for (let i = start; i < end; i++) {
result.push(i);
}
return result;
};
const disabledDate: RangePickerProps['disabledDate'] = (current) => {
// Can not select days before today and today
return current && current < dayjs().endOf('day');
};
const disabledDateForMonth: RangePickerProps['disabledDate'] = (current) => {
// Can not select months before this month
return current && current < dayjs().startOf('month');
};
const disabledDateTime = () => ({
disabledHours: () => range(0, 24).splice(4, 20),
disabledMinutes: () => range(30, 60),
disabledSeconds: () => [55, 56],
});
const disabledRangeTime: RangePickerProps['disabledTime'] = (_, type) => {
if (type === 'start') {
return {
disabledHours: () => range(0, 60).splice(4, 20),
disabledMinutes: () => range(30, 60),
disabledSeconds: () => [55, 56],
};
}
return {
disabledHours: () => range(0, 60).splice(20, 4),
disabledMinutes: () => range(0, 31),
disabledSeconds: () => [55, 56],
};
};
const App: React.FC = () => (
);
export default App;
```
### Allow Empty
Allow empty for the RangePicker. It's useful when you need to keep the "to date".
```tsx
import React from 'react';
import { DatePicker } from 'antd';
const App: React.FC = () => (
{
console.log(date, dateString);
}}
/>
);
export default App;
```
### Select range dates
Using `info.from` of `disabledDate` to limit the dynamic date range selection.
```tsx
import React from 'react';
import { DatePicker, Space, Typography } from 'antd';
import type { DatePickerProps } from 'antd';
import type { Dayjs } from 'dayjs';
const { RangePicker } = DatePicker;
const getYearMonth = (date: Dayjs) => date.year() * 12 + date.month();
// Disabled 7 days from the selected date
const disabled7DaysDate: DatePickerProps['disabledDate'] = (current, { from, type }) => {
if (from) {
const minDate = from.add(-6, 'days');
const maxDate = from.add(6, 'days');
switch (type) {
case 'year':
return current.year() < minDate.year() || current.year() > maxDate.year();
case 'month':
return (
getYearMonth(current) < getYearMonth(minDate) ||
getYearMonth(current) > getYearMonth(maxDate)
);
default:
return Math.abs(current.diff(from, 'days')) >= 7;
}
}
return false;
};
// Disabled 6 months from the selected date
const disabled6MonthsDate: DatePickerProps['disabledDate'] = (current, { from, type }) => {
if (from) {
const minDate = from.add(-5, 'months');
const maxDate = from.add(5, 'months');
switch (type) {
case 'year':
return current.year() < minDate.year() || current.year() > maxDate.year();
default:
return (
getYearMonth(current) < getYearMonth(minDate) ||
getYearMonth(current) > getYearMonth(maxDate)
);
}
}
return false;
};
const App: React.FC = () => (
7 days range
6 months range
);
export default App;
```
### Preset Ranges
We can set preset ranges to RangePicker to improve user experience. Since `5.8.0`, preset value supports callback function.
```tsx
import React from 'react';
import type { TimeRangePickerProps } from 'antd';
import { DatePicker, Space } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
const { RangePicker } = DatePicker;
const onChange = (date: Dayjs | null) => {
if (date) {
console.log('Date: ', date);
} else {
console.log('Clear');
}
};
const onRangeChange = (dates: null | (Dayjs | null)[], dateStrings: string[]) => {
if (dates) {
console.log('From: ', dates[0], ', to: ', dates[1]);
console.log('From: ', dateStrings[0], ', to: ', dateStrings[1]);
} else {
console.log('Clear');
}
};
const rangePresets: TimeRangePickerProps['presets'] = [
{ label: 'Last 7 Days', value: [dayjs().add(-7, 'd'), dayjs()] },
{ label: 'Last 14 Days', value: [dayjs().add(-14, 'd'), dayjs()] },
{ label: 'Last 30 Days', value: [dayjs().add(-30, 'd'), dayjs()] },
{ label: 'Last 90 Days', value: [dayjs().add(-90, 'd'), dayjs()] },
];
const App: React.FC = () => (
Now ~ EOD,
value: () => [dayjs(), dayjs().endOf('day')], // 5.8.0+ support function
},
...rangePresets,
]}
showTime
format="YYYY/MM/DD HH:mm:ss"
onChange={onRangeChange}
/>
);
export default App;
```
### Extra Footer
Render extra footer in panel for customized requirements.
```tsx
import React from 'react';
import { DatePicker, Space } from 'antd';
const { RangePicker } = DatePicker;
const App: React.FC = () => (
'extra footer'} />
'extra footer'} showTime />
'extra footer'} />
'extra footer'} showTime />
'extra footer'} picker="month" />
);
export default App;
```
### Three Sizes
The input box comes in three sizes: small, medium and large. The `medium` size will be used if `size` is omitted.
```tsx
import React, { useState } from 'react';
import type { ConfigProviderProps, RadioChangeEvent } from 'antd';
import { DatePicker, Radio, Space } from 'antd';
type SizeType = ConfigProviderProps['componentSize'];
const { RangePicker } = DatePicker;
const App: React.FC = () => {
const [size, setSize] = useState('medium');
const handleSizeChange = (e: RadioChangeEvent) => {
setSize(e.target.value);
};
return (
Large
Medium
Small
);
};
export default App;
```
### Customized Cell Rendering
We can customize the rendering of the cells in the calendar by providing a `cellRender` function to `DatePicker`.
```tsx
import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Space, theme } from 'antd';
import type { Dayjs } from 'dayjs';
const App: React.FC = () => {
const { token } = theme.useToken();
const style: React.CSSProperties = {
border: `1px solid ${token.colorPrimary}`,
borderRadius: '50%',
};
const cellRender: DatePickerProps['cellRender'] = (current, info) => {
if (info.type !== 'date') {
return info.originNode;
}
if (typeof current === 'number' || typeof current === 'string') {
return {current}
;
}
return (
{current.date()}
);
};
return (
);
};
export default App;
```
### Customize Panel
Replace panel with `components`.
```tsx
import React from 'react';
import type { DatePickerProps } from 'antd';
import { Button, DatePicker, Flex, Slider, Space, Typography } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
const onChange: DatePickerProps['onChange'] = (date, dateString) => {
console.log(date, dateString);
};
type DateComponent = Required['components']>>['date'];
type GetProps = T extends React.ComponentType ? P : never;
const MyDatePanel = (props: GetProps) => {
const { value, onSelect, onHover } = props;
// Value
const startDate = React.useMemo(() => dayjs().date(1).month(0), []);
const [innerValue, setInnerValue] = React.useState(value || startDate);
React.useEffect(() => {
if (value) {
setInnerValue(value);
}
}, [value]);
// Range
const dateCount = React.useMemo(() => {
const endDate = startDate.add(1, 'year').add(-1, 'day');
return endDate.diff(startDate, 'day');
}, [startDate]);
const sliderValue = Math.min(Math.max(0, innerValue.diff(startDate, 'day')), dateCount);
// Render
return (
The BEST Picker Panel
{
const nextDate = startDate.add(nextValue, 'day');
setInnerValue(nextDate);
onHover?.(nextDate);
}}
tooltip={{
formatter: (nextValue) => startDate.add(nextValue || 0, 'day').format('YYYY-MM-DD'),
}}
/>
{
onSelect(innerValue);
}}
>{`That's It!`}
);
};
const App: React.FC = () => (
);
export default App;
```
### External use panel
Custom menu, external selection panel.
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import { DatePicker, Dropdown, Space } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
const DatePickerDemo: React.FC = () => {
const [visible, setVisible] = React.useState(false);
const [panelVisible, setPanelVisible] = React.useState(false);
const [date, setDate] = React.useState(() => dayjs());
return (
{
setVisible(open);
if (!open) {
setPanelVisible(false);
}
}}
menu={{
items: [
{
key: 'today',
label: 'Today',
onClick() {
setDate(dayjs());
setVisible(false);
},
},
{
key: 'tomorrow',
label: 'Tomorrow',
onClick() {
setDate(dayjs().add(1, 'day'));
setVisible(false);
},
},
{
key: 'custom-date',
label: (
{
e.stopPropagation();
setPanelVisible(true);
}}
>
Customize
{
e.stopPropagation();
}}
>
{
setDate(date);
setVisible(false);
setPanelVisible(false);
}}
/>
),
},
],
}}
>
{date?.format('YYYY-MM-DD')}
);
};
const RangePickerDemo: React.FC = () => {
const [visible, setVisible] = React.useState(false);
const [panelVisible, setPanelVisible] = React.useState(false);
const [dates, setDates] = React.useState<[Dayjs, Dayjs] | null>(() => [
dayjs(),
dayjs().add(1, 'day'),
]);
return (
{
setVisible(open);
if (!open) {
setPanelVisible(false);
}
}}
menu={{
items: [
{
key: '7',
label: '7 days',
onClick() {
setDates([dayjs(), dayjs().add(7, 'day')]);
setVisible(false);
},
},
{
key: '30',
label: '30 days',
onClick() {
setDates([dayjs(), dayjs().add(30, 'day')]);
setVisible(false);
},
},
{
key: 'custom-date',
label: (
{
e.stopPropagation();
setPanelVisible(true);
}}
>
Customize
{
e.stopPropagation();
}}
>
{
if (ranges?.[0] && ranges?.[1]) {
setDates([ranges[0], ranges[1]]);
} else {
setDates(null);
}
setVisible(false);
setPanelVisible(false);
}}
/>
),
},
],
}}
>
{dates
? `${dates[0].format('YYYY-MM-DD')} ~ ${dates[1].format('YYYY-MM-DD')}`
: 'Select range'}
);
};
const Demo = () => {
return (
);
};
export default Demo;
```
### Buddhist Era
Use `locale` to support special calendar format.
```tsx
import React from 'react';
import { ConfigProvider, DatePicker, Space, Typography } from 'antd';
import type { DatePickerProps } from 'antd';
import en from 'antd/es/date-picker/locale/en_US';
import enUS from 'antd/es/locale/en_US';
import dayjs from 'dayjs';
import buddhistEra from 'dayjs/plugin/buddhistEra';
dayjs.extend(buddhistEra);
const { Title } = Typography;
// Component level locale
const buddhistLocale: typeof en = {
...en,
lang: {
...en.lang,
fieldDateFormat: 'BBBB-MM-DD',
fieldDateTimeFormat: 'BBBB-MM-DD HH:mm:ss',
yearFormat: 'BBBB',
cellYearFormat: 'BBBB',
},
};
// ConfigProvider level locale
const globalBuddhistLocale: typeof enUS = {
...enUS,
DatePicker: {
...enUS.DatePicker!,
lang: buddhistLocale.lang,
},
};
const defaultValue = dayjs('2024-01-01');
const App: React.FC = () => {
const onChange: DatePickerProps['onChange'] = (_, dateStr) => {
console.log('onChange:', dateStr);
};
return (
By locale props
By ConfigProvider
);
};
export default App;
```
### Status
Add status to DatePicker with `status`, which could be `error` or `warning`.
```tsx
import React from 'react';
import { DatePicker, Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Variants
Variants of DatePicker, there are four variants: `outlined` `filled` `borderless` and `underlined`.
```tsx
import React from 'react';
import { DatePicker, Flex } from 'antd';
const { RangePicker } = DatePicker;
const App: React.FC = () => (
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of DatePicker by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { DatePicker, Flex } from 'antd';
import type { DatePickerProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
import type { Dayjs } from 'dayjs';
const useStyles = createStyles(({ token }) => ({
root: {
border: `1px solid ${token.colorPrimary}`,
width: 200,
},
}));
const stylesObject: DatePickerProps['styles'] = {
input: { fontStyle: 'italic' },
suffix: { opacity: 0.85 },
};
const stylesFn: DatePickerProps['styles'] = (
info,
): GetProp, 'styles', 'Return'> => {
if (info.props.size === 'large') {
return {
root: { borderColor: '#722ed1' },
popup: {
container: { border: '1px solid #722ed1', borderRadius: 8 },
},
};
}
return {};
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
return (
);
};
export default App;
```
### Placement
You can manually specify the position of the popup via `placement`.
```tsx
import React, { useState } from 'react';
import type { DatePickerProps, RadioChangeEvent } from 'antd';
import { DatePicker, Radio } from 'antd';
const { RangePicker } = DatePicker;
const App: React.FC = () => {
const [placement, setPlacement] = useState('topLeft');
const placementChange = (e: RadioChangeEvent) => {
setPlacement(e.target.value);
};
return (
<>
topLeft
topRight
bottomLeft
bottomRight
>
);
};
export default App;
```
### Prefix and Suffix
Custom `prefix` and `suffixIcon`.
```tsx
import React from 'react';
import { SmileOutlined } from '@ant-design/icons';
import { DatePicker, Space } from 'antd';
import type { Dayjs } from 'dayjs';
const smileIcon = ;
const { RangePicker } = DatePicker;
const onChange = (date: Dayjs | (Dayjs | null)[] | null, dateString: string | string[] | null) => {
console.log(date, dateString);
};
const App: React.FC = () => (
);
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
There are five kinds of picker:
- DatePicker
- DatePicker\[picker="month"]
- DatePicker\[picker="week"]
- DatePicker\[picker="year"]
- DatePicker\[picker="quarter"] (Added in 4.1.0)
- RangePicker
### Localization
The default locale is en-US, if you need to use other languages, recommend to use internationalized components provided by us at the entrance. Look at: [ConfigProvider](https://ant.design/components/config-provider/).
If there are special needs (only modifying single component language), Please use the property: locale. Example: [default](https://github.com/ant-design/ant-design/blob/master/components/date-picker/locale/example.json).
```jsx
// The default locale is en-US, if you want to use other locale, just set locale in entry file globally.
// Make sure you import the relevant dayjs file as well, otherwise the locale won't change for all texts (e.g. range picker months)
import locale from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');
;
```
:::warning
When using the Next.js App Router, make sure to add `'use client'` before importing Day.js locale files. This is because all Ant Design components only work on the client side, so importing locale files in RSC will not work.
:::
### Common API
The following APIs are shared by DatePicker, RangePicker.
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| allowClear | Customize clear button | boolean \| { clearIcon?: ReactNode } | true | 5.8.0: Support object type | 6.4.0 |
| ~~bordered~~ | Whether has border style, please use `variant` instead | boolean | true | - | × |
| className | The picker className | string | - | | DatePicker: 5.7.0, RangePicker: 5.11.0 |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | DatePicker: 5.25.0, RangePicker: 5.25.0 |
| dateRender | Custom rendering function for date cells, >= 5.4.0 use `cellRender` instead. | function(currentDate: dayjs, today: dayjs) => React.ReactNode | - | < 5.4.0 | × |
| cellRender | Custom rendering function for picker cells | (current: dayjs, info: { originNode: React.ReactElement,today: DateType, range?: 'start' \| 'end', type: PanelMode, locale?: Locale, subType?: 'hour' \| 'minute' \| 'second' \| 'meridiem' }) => React.ReactNode | - | 5.4.0 | × |
| components | Custom panels | Record | - | 5.14.0 | × |
| defaultOpen | Initial open state of picker | boolean | - | | × |
| disabled | Determine whether the DatePicker is disabled | boolean | false | | × |
| disabledDate | Specify the date that cannot be selected | (currentDate: dayjs, info: { from?: dayjs, type: Picker }) => boolean | - | `info`: 5.14.0 | × |
| ~~dropdownClassName~~ | The className of popup calendar, please use `classNames.popup.root` instead | string | - | - | × |
| format | To set the date format, support multi-format matching when it is an array, display the first one shall prevail. refer to [dayjs#format](https://day.js.org/docs/en/display/format). for example: [Custom Format](#date-picker-demo-format) | [formatType](#formattype) | [@rc-component/picker](https://github.com/react-component/picker/blob/f512f18ed59d6791280d1c3d7d37abbb9867eb0b/src/utils/uiUtil.ts#L155-L177) | | × |
| order | Auto order date when multiple or range selection | boolean | true | 5.14.0 | × |
| ~~popupClassName~~ | To customize the className of the popup calendar, use `classNames.popup.root` instead | string | - | 4.23.0 | × |
| preserveInvalidOnBlur | Don't clear the input on blur even when the typed value is invalid | boolean | false | 5.14.0 | × |
| getPopupContainer | To set the container of the floating layer, while the default is to create a `div` element in `body` | function(trigger) | - | | × |
| inputReadOnly | Set the `readonly` attribute of the input tag (avoids virtual keyboard on touch devices) | boolean | false | | × |
| locale | Localization configuration | object | [default](https://github.com/ant-design/ant-design/blob/master/components/date-picker/locale/example.json) | | × |
| minDate | The minimum date, which also limits the range of panel switching | dayjs | - | 5.14.0 | × |
| maxDate | The maximum date, which also limits the range of panel switching | dayjs | - | 5.14.0 | × |
| mode | The picker panel mode( [Cannot select year or month anymore?](/docs/react/faq#when-set-mode-to-datepickerrangepicker-cannot-select-year-or-month-anymore) ) | `time` \| `date` \| `month` \| `year` \| `decade` | - | | × |
| needConfirm | Need click confirm button to trigger value change. Default `false` when `multiple` | boolean | - | 5.14.0 | × |
| nextIcon | The custom next icon | ReactNode | - | 4.17.0 | × |
| open | The open state of picker | boolean | - | | × |
| panelRender | Customize panel render | (panelNode) => ReactNode | - | 4.5.0 | × |
| picker | Set picker type | `date` \| `week` \| `month` \| `quarter` \| `year` | `date` | `quarter`: 4.1.0 | × |
| placeholder | The placeholder of date input | string \| \[string,string] | - | | × |
| placement | The position where the selection box pops up | `bottomLeft` `bottomRight` `topLeft` `topRight` | bottomLeft | | × |
| ~~popupStyle~~ | To customize the style of the popup calendar, use `styles.popup.root` instead | CSSProperties | {} | | × |
| prefix | The custom prefix | ReactNode | - | 5.22.0 | × |
| presets | The preset ranges for quick selection, Since `5.8.0`, preset value supports callback function. | { label: React.ReactNode, value: Dayjs \| (() => Dayjs) }\[] | - | | × |
| prevIcon | The custom prev icon | ReactNode | - | 4.17.0 | × |
| previewValue | When the user selects the date hover option, the value of the input field undergoes a temporary change | false \| hover | hover | 6.0.0 | × |
| size | To determine the size of the input box, the height of `large` and `small`, are 40px and 24px respectively, while default size is 32px | `large` \| `medium` \| `small` | - | | × |
| status | Set validation status | 'error' \| 'warning' | - | 4.19.0 | × |
| style | To customize the style of the input box | CSSProperties | {} | | DatePicker: 5.7.0, RangePicker: 5.11.0 |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | DatePicker: 5.25.0, RangePicker: 5.25.0 |
| suffixIcon | The custom suffix icon | ReactNode | - | | DatePicker: 6.3.0, RangePicker: 6.4.0 |
| superNextIcon | The custom super next icon | ReactNode | - | 4.17.0 | × |
| superPrevIcon | The custom super prev icon | ReactNode | - | 4.17.0 | × |
| clearIcon | (Only supports global configuration) Custom clear icon | ReactNode | - | × | 6.4.0 |
| variant | Variants of picker | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 \| `underlined`: 5.24.0 | DatePicker: 5.19.0, RangePicker: 5.19.0 |
| onOpenChange | Callback function, can be executed whether the popup calendar is popped up or closed | function(open) | - | | × |
| onPanelChange | Callback when picker panel mode is changed | function(value, mode) | - | | × |
| ~~onSelect~~ | Callback when a date is selected, please use `onCalendarChange` instead | function(value) | - | - | × |
### Common Methods
| Name | Description | Version |
| ------- | ------------ | ------- |
| blur() | Remove focus | |
| focus() | Get focus | |
### DatePicker
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| defaultPickerValue | Default panel date, will be reset when panel open | [dayjs](https://day.js.org/) | - | 5.14.0 |
| defaultValue | To set default date, if start time or end time is null or undefined, the date range will be an open interval | [dayjs](https://day.js.org/) | - | |
| disabledTime | To specify the time that cannot be selected | function(date) | - | |
| format | To set the date format. refer to [dayjs#format](https://day.js.org/docs/en/display/format) | [formatType](#formattype) | `YYYY-MM-DD` | |
| multiple | Enable multiple selection. Not support `showTime` | boolean | false | 5.14.0 |
| pickerValue | Panel date. Used for controlled switching of panel date. Work with `onPanelChange` | [dayjs](https://day.js.org/) | - | 5.14.0 |
| renderExtraFooter | Render extra footer in panel | (mode) => React.ReactNode | - | |
| showNow | Show the fast access of current datetime | boolean | - | 4.4.0 |
| showTime | To provide an additional time selection | object \| boolean | [TimePicker Options](/components/time-picker/#api) | |
| ~~showTime.defaultValue~~ | Use `showTime.defaultOpenValue` instead | [dayjs](https://day.js.org/) | dayjs() | 5.27.3 |
| showTime.defaultOpenValue | To set default time of selected date, [demo](#date-picker-demo-disabled-date) | [dayjs](https://day.js.org/) | dayjs() | |
| showWeek | Show week info when in DatePicker | boolean | false | 5.14.0 |
| value | To set date | [dayjs](https://day.js.org/) | - | |
| onChange | Callback function, can be executed when the selected time is changing | function(date: dayjs \| null, dateString: string \| null) | - | |
| onOk | Callback when click ok button | function() | - | |
| onPanelChange | Callback function for panel changing | function(value, mode) | - | |
### DatePicker\[picker=year]
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| defaultValue | To set default date | [dayjs](https://day.js.org/) | - | |
| format | To set the date format. refer to [dayjs#format](https://day.js.org/docs/en/display/format) | [formatType](#formattype) | `YYYY` | |
| multiple | Enable multiple selection | boolean | false | 5.14.0 |
| renderExtraFooter | Render extra footer in panel | () => React.ReactNode | - | |
| tagRender | Customize tag render, only applies when `multiple` is set | (props) => ReactNode | - | 6.4.0 |
| value | To set date | [dayjs](https://day.js.org/) | - | |
| onChange | Callback function, can be executed when the selected time is changing | function(date: dayjs \| null, dateString: string \| null) | - | |
### DatePicker\[picker=quarter]
Added in `4.1.0`.
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| defaultValue | To set default date | [dayjs](https://day.js.org/) | - | |
| format | To set the date format. refer to [dayjs#format](https://day.js.org/docs/en/display/format) | [formatType](#formattype) | `YYYY-\QQ` | |
| multiple | Enable multiple selection | boolean | false | 5.14.0 |
| renderExtraFooter | Render extra footer in panel | () => React.ReactNode | - | |
| tagRender | Customize tag render, only applies when `multiple` is set | (props) => ReactNode | - | 6.4.0 |
| value | To set date | [dayjs](https://day.js.org/) | - | |
| onChange | Callback function, can be executed when the selected time is changing | function(date: dayjs \| null, dateString: string \| null) | - | |
### DatePicker\[picker=month]
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| defaultValue | To set default date | [dayjs](https://day.js.org/) | - | |
| format | To set the date format. refer to [dayjs#format](https://day.js.org/docs/en/display/format) | [formatType](#formattype) | `YYYY-MM` | |
| multiple | Enable multiple selection | boolean | false | 5.14.0 |
| renderExtraFooter | Render extra footer in panel | () => React.ReactNode | - | |
| tagRender | Customize tag render, only applies when `multiple` is set | (props) => ReactNode | - | 6.4.0 |
| value | To set date | [dayjs](https://day.js.org/) | - | |
| onChange | Callback function, can be executed when the selected time is changing | function(date: dayjs \| null, dateString: string \| null) | - | |
### DatePicker\[picker=week]
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| defaultValue | To set default date | [dayjs](https://day.js.org/) | - | |
| format | To set the date format. refer to [dayjs#format](https://day.js.org/docs/en/display/format) | [formatType](#formattype) | `YYYY-wo` | |
| multiple | Enable multiple selection | boolean | false | 5.14.0 |
| renderExtraFooter | Render extra footer in panel | (mode) => React.ReactNode | - | |
| tagRender | Customize tag render, only applies when `multiple` is set | (props) => ReactNode | - | 6.4.0 |
| value | To set date | [dayjs](https://day.js.org/) | - | |
| onChange | Callback function, can be executed when the selected time is changing | function(date: dayjs \| null, dateString: string \| null) | - | |
| showWeek | Show week info when in DatePicker | boolean | true | 5.14.0 |
### RangePicker
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| allowEmpty | Allow start or end input leave empty | \[boolean, boolean] | \[false, false] | | × |
| cellRender | Custom rendering function for picker cells | (current: dayjs, info: { originNode: React.ReactElement,today: DateType, range?: 'start' \| 'end', type: PanelMode, locale?: Locale, subType?: 'hour' \| 'minute' \| 'second' \| 'meridiem' }) => React.ReactNode | - | 5.4.0 | × |
| dateRender | Custom rendering function for date cells, >= 5.4.0 use `cellRender` instead. | function(currentDate: dayjs, today: dayjs) => React.ReactNode | - | < 5.4.0 | × |
| defaultPickerValue | Default panel date, will be reset when panel open | \[[dayjs](https://day.js.org/), [dayjs](https://day.js.org/)] | - | 5.14.0 | × |
| defaultValue | To set default date | \[[dayjs](https://day.js.org/), [dayjs](https://day.js.org/)] | - | | × |
| disabled | If disable start or end | \[boolean, boolean] | - | | × |
| disabledTime | To specify the time that cannot be selected | function(date: dayjs, partial: `start` \| `end`, info: { from?: dayjs }) | - | `info.from`: 5.17.0 | × |
| format | To set the date format. refer to [dayjs#format](https://day.js.org/docs/en/display/format) | [formatType](#formattype) | `YYYY-MM-DD HH:mm:ss` | | × |
| id | Config input ids | { start?: string, end?: string } | - | 5.14.0 | × |
| pickerValue | Panel date. Used for controlled switching of panel date. Work with `onPanelChange` | \[[dayjs](https://day.js.org/), [dayjs](https://day.js.org/)] | - | 5.14.0 | × |
| presets | The preset ranges for quick selection, Since `5.8.0`, preset value supports callback function. | { label: React.ReactNode, value: \[(Dayjs \| (() => Dayjs)), (Dayjs \| (() => Dayjs))] }\[] | - | | × |
| renderExtraFooter | Render extra footer in panel | () => React.ReactNode | - | | × |
| separator | Set separator between inputs | React.ReactNode | ` ` | | 6.3.0 |
| showTime | To provide an additional time selection | object \| boolean | [TimePicker Options](/components/time-picker/#api) | | × |
| ~~showTime.defaultValue~~ | Use `showTime.defaultOpenValue` instead | \[[dayjs](https://day.js.org/), [dayjs](https://day.js.org/)] | \[dayjs(), dayjs()] | 5.27.3 | × |
| showTime.defaultOpenValue | To set default time of selected date, [demo](#date-picker-demo-disabled-date) | \[[dayjs](https://day.js.org/), [dayjs](https://day.js.org/)] | \[dayjs(), dayjs()] | | × |
| value | To set date | \[[dayjs](https://day.js.org/), [dayjs](https://day.js.org/)] | - | | × |
| onCalendarChange | Callback function, can be executed when the start time or the end time of the range is changing. `info` argument is added in 4.4.0 | function(dates: \[dayjs, dayjs], dateStrings: \[string, string], info: { range:`start`\|`end` }) | - | | × |
| onChange | Callback function, can be executed when the selected time is changing | function(dates: \[dayjs, dayjs] \| null, dateStrings: \[string, string] \| null) | - | | × |
| onFocus | Trigger when get focus | function(event, { range: 'start' \| 'end' }) | - | `range`: 5.14.0 | × |
| onBlur | Trigger when lose focus | function(event, { range: 'start' \| 'end' }) | - | `range`: 5.14.0 | × |
#### formatType
```typescript
import type { Dayjs } from 'dayjs';
type Generic = string;
type GenericFn = (value: Dayjs) => string;
export type FormatType =
| Generic
| GenericFn
| Array
| {
format: string;
type?: 'mask';
};
```
Note: `type` is added in `5.14.0`.
## Semantic DOM
https://ant.design/components/date-picker/semantic.md
## Design Token
## Component Token (DatePicker)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| activeBg | Background color when the input box is activated | string | #ffffff |
| activeBorderColor | Active border color | string | #1677ff |
| activeShadow | Box-shadow when active | string | 0 0 0 2px rgba(5,145,255,0.1) |
| addonBg | Background color of addon | string | rgba(0,0,0,0.02) |
| cellActiveWithRangeBg | Background color of cell in range | string | #e6f4ff |
| cellBgDisabled | Background color of disabled cell | string | rgba(0,0,0,0.04) |
| cellHeight | Height of cell | number | 24 |
| cellHoverBg | Background color of cell hover state | string | rgba(0,0,0,0.04) |
| cellHoverWithRangeBg | Background color of hovered cell in range | string | #cbe0fd |
| cellRangeBorderColor | Border color of cell in range when picking | string | #82b4f9 |
| cellWidth | Width of cell | number | 36 |
| errorActiveShadow | Box-shadow when active in error status | string | 0 0 0 2px rgba(255,38,5,0.06) |
| hoverBg | Background color when the input box hovers | string | #ffffff |
| hoverBorderColor | Hover border color | string | #4096ff |
| inputFontSize | Font size | number | 14 |
| inputFontSizeLG | Font size of large | number | 16 |
| inputFontSizeSM | Font size of small | number | 14 |
| multipleItemBg | Background color of multiple tag | string | rgba(0,0,0,0.06) |
| multipleItemBorderColor | Border color of multiple tag | string | transparent |
| multipleItemBorderColorDisabled | Border color of multiple tag when disabled | string | transparent |
| multipleItemColorDisabled | Text color of multiple tag when disabled | string | rgba(0,0,0,0.25) |
| multipleItemHeight | Height of multiple tag | number | 24 |
| multipleItemHeightLG | Height of multiple tag with large size | number | 32 |
| multipleItemHeightSM | Height of multiple tag with small size | number | 16 |
| multipleSelectorBgDisabled | Background color of multiple selector when disabled | string | rgba(0,0,0,0.04) |
| paddingBlock | Vertical padding of input | number | 4 |
| paddingBlockLG | Vertical padding of large input | number | 7 |
| paddingBlockSM | Vertical padding of small input | number | 0 |
| paddingInline | Horizontal padding of input | number | 11 |
| paddingInlineLG | Horizontal padding of large input | number | 11 |
| paddingInlineSM | Horizontal padding of small input | number | 7 |
| presetsMaxWidth | Max width of preset area | number | 200 |
| presetsWidth | Width of preset area | number | 120 |
| textHeight | Height of cell text | number | 40 |
| timeCellHeight | Height of time cell | number | 28 |
| timeColumnHeight | Height of time column | number | 224 |
| timeColumnWidth | Width of time column | number | 56 |
| warningActiveShadow | Box-shadow when active in warning status | string | 0 0 0 2px rgba(255,215,5,0.1) |
| withoutTimeCellHeight | Height of decade/year/quarter/month/week cell | number | 66 |
| zIndexPopup | z-index of popup | number | 1050 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadius | Border radius of base components | number | |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| borderRadiusXS | XS size border radius, used in some small border radius components, such as Segmented, Arrow and other components with small border radius. | number | |
| boxShadowSecondary | Control the secondary box shadow style of an element. | string | |
| colorBgContainer | Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. | string | |
| colorBgContainerDisabled | Control the background color of container in disabled state. | string | |
| colorBgElevated | Container background color of the popup layer, in dark mode the color value of this token will be a little brighter than `colorBgContainer`. E.g: modal, pop-up, menu, etc. | string | |
| colorBorder | Default border color, used to separate different elements, such as: form separator, card separator, etc. | string | |
| colorBorderDisabled | Control the border color of the element in the disabled state. | string | |
| colorError | Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. | string | |
| colorErrorAffix | Control the color of form control prefix/suffix in error state. | string | |
| colorErrorBg | The background color of the error state. | string | |
| colorErrorBgHover | The hover state background color of the error state. | string | |
| colorErrorBorderHover | The hover state border color of the error state. | string | |
| colorErrorText | The default state of the text in the error color. | string | |
| colorFillSecondary | The second level of fill color can outline the shape of the element more clearly, such as Rate, Skeleton, etc. It can also be used as the Hover state of the third level of fill color, such as Table, etc. | string | |
| colorFillTertiary | The third level of fill color is used to outline the shape of the element, such as Slider, Segmented, etc. If there is no emphasis requirement, it is recommended to use the third level of fill color as the default fill color. | string | |
| colorIcon | Weak action. Such as `allowClear` or Alert close button | string | |
| colorIconHover | Weak action hover color. Such as `allowClear` or Alert close button | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorSplit | Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDisabled | Control the color of text in disabled state. | string | |
| colorTextHeading | Control the font color of heading. | string | |
| colorTextLightSolid | Control the highlight color of text with background color, such as the text in Primary Button components. | string | |
| colorTextPlaceholder | Control the color of placeholder text. | string | |
| colorTextQuaternary | The fourth level of text color is the lightest text color, such as form input prompt text, disabled color text, etc. | string | |
| colorTextTertiary | The third level of text color is generally used for descriptive text, such as form supplementary explanation text, list descriptive text, etc. | string | |
| colorWarning | Used to represent the warning map token, such as Notification, Alert, etc. Alert or Control component(like Input) will use these map tokens. | string | |
| colorWarningAffix | Control the color of form control prefix/suffix in warning state. | string | |
| colorWarningBg | The background color of the warning state. | string | |
| colorWarningBgHover | The hover state background color of the warning state. | string | |
| colorWarningBorderHover | The hover state border color of the warning state. | string | |
| colorWarningText | The default state of the text in the warning color. | string | |
| controlHeight | The height of the basic controls such as buttons and input boxes in Ant Design | number | |
| controlHeightLG | LG component height | number | |
| controlHeightSM | SM component height | number | |
| controlItemBgActive | Control the background color of control component item when active. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeLG | Large font size | number | |
| fontSizeSM | Small font size | number | |
| fontWeightStrong | Control the font weight of heading components (such as h1, h2, h3) or selected item. | number | |
| lineHeight | Line height of text. | number | |
| lineHeightLG | Line height of large text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| lineWidthBold | The default line width of the outline class components, such as Button, Input, Select, etc. | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseInOutCirc | Preset motion curve. | string | |
| motionEaseInQuint | Preset motion curve. | string | |
| motionEaseOutCirc | Preset motion curve. | string | |
| motionEaseOutQuint | Preset motion curve. | string | |
| padding | Control the padding of the element. | number | |
| paddingSM | Control the small padding of the element. | number | |
| paddingXS | Control the extra small padding of the element. | number | |
| paddingXXS | Control the extra extra small padding of the element. | number | |
| sizePopupArrow | The size of the component arrow | number | |
## FAQ
### When set mode to DatePicker/RangePicker, cannot select year or month anymore? {#faq-mode-cannot-select}
Please refer [FAQ](/docs/react/faq#when-set-mode-to-datepickerrangepicker-cannot-select-year-or-month-anymore)
### Why does the date picker switch to the date panel after selecting the year instead of the month panel? {#faq-year-to-date-panel}
After selecting the year, the system directly switches to the date panel instead of month panel. This design is intended to reduce the user's operational burden by allowing them to complete the year modification with just one click, without having to enter the month selection interface again. At the same time, it also avoids additional cognitive burden of remembering the month.
### How to use DatePicker with customize date library like dayjs? {#faq-custom-date-library}
Please refer [Use custom date library](/docs/react/use-custom-date-library#datepicker)
### Why config dayjs.locale globally not work? {#faq-locale-not-work}
DatePicker default set `locale` as `en` in v4. You can config DatePicker `locale` prop or [ConfigProvider `locale`](/components/config-provider) prop instead.
#### Date-related components locale is not working?
See FAQ [Date-related-components-locale-is-not-working?](/docs/react/faq#date-related-components-locale-is-not-working)
### How to modify start day of week? {#faq-week-start-day}
Please use correct [language](/docs/react/i18n) ([#5605](https://github.com/ant-design/ant-design/issues/5605)), or update dayjs `locale` config:
- Example:
```js
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import updateLocale from 'dayjs/plugin/updateLocale';
dayjs.extend(updateLocale);
dayjs.updateLocale('zh-cn', {
weekStart: 0,
});
```
### Why origin panel don't switch when using `panelRender`? {#faq-panel-render-switch}
When you change the layout of nodes by `panelRender`, React will unmount and re-mount it which reset the component state. You should keep the layout stable. Please ref [#27263](https://github.com/ant-design/ant-design/issues/27263) for more info.
### How to understand disabled time and date? {#faq-disabled-date-time}
Please refer to the blog ['Why is it so hard to disable the date?'](/docs/blog/picker), to learn how to use it.
---
## descriptions
Source: https://ant.design/components/descriptions.md
---
category: Components
group: Data Display
title: Descriptions
description: Display multiple read-only fields in a group.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*fHdlTpif6XQAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*d27AQJrowGAAAAAAAAAAAAAADrJ8AQ/original
---
## When To Use
Commonly displayed on the details page.
```tsx | pure
// works when >= 5.8.0, recommended ✅
const items: DescriptionsProps['items'] = [
{
key: '1',
label: 'UserName',
children: Zhou Maomao
,
},
{
key: '2',
label: 'Telephone',
children: 1810000000
,
},
{
key: '3',
label: 'Live',
children: Hangzhou, Zhejiang
,
},
{
key: '4',
label: 'Remark',
children: empty
,
},
{
key: '5',
label: 'Address',
children: No. 18, Wantang Road, Xihu District, Hangzhou, Zhejiang, China
,
},
];
;
// works when <5.8.0 , deprecated when >=5.8.0 🙅🏻♀️
Zhou Maomao
1810000000
Hangzhou, Zhejiang
empty
No. 18, Wantang Road, Xihu District, Hangzhou, Zhejiang, China
;
```
## Examples
### Basic
Simplest Usage.
```tsx
import React from 'react';
import { Descriptions } from 'antd';
import type { DescriptionsProps } from 'antd';
const items: DescriptionsProps['items'] = [
{
key: '1',
label: 'UserName',
children: 'Zhou Maomao',
},
{
key: '2',
label: 'Telephone',
children: '1810000000',
},
{
key: '3',
label: 'Live',
children: 'Hangzhou, Zhejiang',
},
{
key: '4',
label: 'Remark',
children: 'empty',
},
{
key: '5',
label: 'Address',
children: 'No. 18, Wantang Road, Xihu District, Hangzhou, Zhejiang, China',
},
];
const App: React.FC = () => ;
export default App;
```
### border
Descriptions with border and background color.
```tsx
import React from 'react';
import { Badge, Descriptions } from 'antd';
import type { DescriptionsProps } from 'antd';
const items: DescriptionsProps['items'] = [
{
key: '1',
label: 'Product',
children: 'Cloud Database',
},
{
key: '2',
label: 'Billing Mode',
children: 'Prepaid',
},
{
key: '3',
label: 'Automatic Renewal',
children: 'YES',
},
{
key: '4',
label: 'Order time',
children: '2018-04-24 18:00:00',
},
{
key: '5',
label: 'Usage Time',
children: '2019-04-24 18:00:00',
span: 2,
},
{
key: '6',
label: 'Status',
children: ,
span: 3,
},
{
key: '7',
label: 'Negotiated Amount',
children: '$80.00',
},
{
key: '8',
label: 'Discount',
children: '$20.00',
},
{
key: '9',
label: 'Official Receipts',
children: '$60.00',
},
{
key: '10',
label: 'Config Info',
children: (
<>
Data disk type: MongoDB
Database version: 3.4
Package: dds.mongo.mid
Storage space: 10 GB
Replication factor: 3
Region: East China 1
>
),
},
];
const App: React.FC = () => ;
export default App;
```
### Custom size
Custom sizes to fit in a variety of containers.
```tsx
import React, { useState } from 'react';
import { Button, Descriptions, Radio } from 'antd';
import type { DescriptionsProps, RadioChangeEvent } from 'antd';
const borderedItems: DescriptionsProps['items'] = [
{
key: '1',
label: 'Product',
children: 'Cloud Database',
},
{
key: '2',
label: 'Billing',
children: 'Prepaid',
},
{
key: '3',
label: 'Time',
children: '18:00:00',
},
{
key: '4',
label: 'Amount',
children: '$80.00',
},
{
key: '5',
label: 'Discount',
children: '$20.00',
},
{
key: '6',
label: 'Official',
children: '$60.00',
},
{
key: '7',
label: 'Config Info',
children: (
<>
Data disk type: MongoDB
Database version: 3.4
Package: dds.mongo.mid
Storage space: 10 GB
Replication factor: 3
Region: East China 1
>
),
},
];
const items: DescriptionsProps['items'] = [
{
key: '1',
label: 'Product',
children: 'Cloud Database',
},
{
key: '2',
label: 'Billing',
children: 'Prepaid',
},
{
key: '3',
label: 'Time',
children: '18:00:00',
},
{
key: '4',
label: 'Amount',
children: '$80.00',
},
{
key: '5',
label: 'Discount',
children: '$20.00',
},
{
key: '6',
label: 'Official',
children: '$60.00',
},
];
const App: React.FC = () => {
const [size, setSize] = useState<'large' | 'medium' | 'small'>('large');
const onChange = (e: RadioChangeEvent) => {
console.log('size checked', e.target.value);
setSize(e.target.value);
};
return (
large
medium
small
Edit}
items={borderedItems}
/>
Edit}
items={items}
/>
);
};
export default App;
```
### responsive
Responsive configuration enables perfect presentation on small screen devices.
```tsx
import React from 'react';
import { Descriptions } from 'antd';
import type { DescriptionsProps } from 'antd';
const items: DescriptionsProps['items'] = [
{
label: 'Product',
children: 'Cloud Database',
},
{
label: 'Billing',
children: 'Prepaid',
},
{
label: 'Time',
children: '18:00:00',
},
{
label: 'Amount',
children: '$80.00',
},
{
label: 'Discount',
span: { xl: 2, xxl: 2 },
children: '$20.00',
},
{
label: 'Official',
span: { xl: 2, xxl: 2 },
children: '$60.00',
},
{
label: 'Config Info',
span: { xs: 1, sm: 2, md: 3, lg: 3, xl: 2, xxl: 2 },
children: (
<>
Data disk type: MongoDB
Database version: 3.4
Package: dds.mongo.mid
>
),
},
{
label: 'Hardware Info',
span: { xs: 1, sm: 2, md: 3, lg: 3, xl: 2, xxl: 2 },
children: (
<>
CPU: 6 Core 3.5 GHz
Storage space: 10 GB
Replication factor: 3
Region: East China 1
>
),
},
];
const App: React.FC = () => (
);
export default App;
```
### Vertical
Simplest Usage.
```tsx
import React from 'react';
import { Descriptions } from 'antd';
import type { DescriptionsProps } from 'antd';
const items: DescriptionsProps['items'] = [
{
key: '1',
label: 'UserName',
children: 'Zhou Maomao',
},
{
key: '2',
label: 'Telephone',
children: '1810000000',
},
{
key: '3',
label: 'Live',
children: 'Hangzhou, Zhejiang',
},
{
key: '4',
label: 'Address',
span: 2,
children: 'No. 18, Wantang Road, Xihu District, Hangzhou, Zhejiang, China',
},
{
key: '5',
label: 'Remark',
children: 'empty',
},
];
const App: React.FC = () => ;
export default App;
```
### Vertical border
Descriptions with border and background color.
```tsx
import React from 'react';
import { Badge, Descriptions } from 'antd';
import type { DescriptionsProps } from 'antd';
const items: DescriptionsProps['items'] = [
{
key: '1',
label: 'Product',
children: 'Cloud Database',
},
{
key: '2',
label: 'Billing Mode',
children: 'Prepaid',
},
{
key: '3',
label: 'Automatic Renewal',
children: 'YES',
},
{
key: '4',
label: 'Order time',
children: '2018-04-24 18:00:00',
},
{
key: '5',
label: 'Usage Time',
span: 2,
children: '2019-04-24 18:00:00',
},
{
key: '6',
label: 'Status',
span: 3,
children: ,
},
{
key: '7',
label: 'Negotiated Amount',
children: '$80.00',
},
{
key: '8',
label: 'Discount',
children: '$20.00',
},
{
key: '9',
label: 'Official Receipts',
children: '$60.00',
},
{
key: '10',
label: 'Config Info',
children: (
<>
Data disk type: MongoDB
Database version: 3.4
Package: dds.mongo.mid
Storage space: 10 GB
Replication factor: 3
Region: East China 1
>
),
},
];
const App: React.FC = () => (
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Descriptions by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Descriptions, Flex } from 'antd';
import type { DescriptionsProps, GetProp } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
padding: 10px;
`,
}));
const items: DescriptionsProps['items'] = [
{
key: '1',
label: 'Product',
children: 'Cloud Database',
},
{
key: '2',
label: 'Billing Mode',
children: 'Prepaid',
},
{
key: '3',
label: 'Automatic Renewal',
children: 'YES',
},
];
const styles: DescriptionsProps['styles'] = {
label: {
color: '#000',
},
};
const stylesFn: DescriptionsProps['styles'] = (
info,
): GetProp => {
if (info.props.size === 'large') {
return {
root: {
borderRadius: 8,
border: '1px solid #CDC1FF',
},
label: { color: '#A294F9' },
};
}
return {};
};
const App: React.FC = () => {
const descriptionsProps: DescriptionsProps = {
title: 'User Info',
items,
bordered: true,
classNames,
};
return (
);
};
export default App;
```
### row
Display of the entire line.
```tsx
import React from 'react';
import { Descriptions } from 'antd';
import type { DescriptionsProps } from 'antd';
const items: DescriptionsProps['items'] = [
{
label: 'UserName',
children: 'Zhou Maomao',
},
{
label: 'Live',
span: 'filled', // span = 2
children: 'Hangzhou, Zhejiang',
},
{
label: 'Remark',
span: 'filled', // span = 3
children: 'empty',
},
{
label: 'Address',
span: 1, // span will be 3 and warning for span is not align to the end
children: 'No. 18, Wantang Road, Xihu District, Hangzhou, Zhejiang, China',
},
];
const App: React.FC = () => ;
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Descriptions
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| bordered | Whether to display the border | boolean | false | | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.23.0 |
| colon | Change default props `colon` value of Descriptions.Item. Indicates whether the colon after the label is displayed | boolean | true | | × |
| column | The number of `DescriptionItems` in a row, could be an object (like `{ xs: 8, sm: 16, md: 24}`, but must have `bordered={true}`) or a number | number \| [Record](https://github.com/ant-design/ant-design/blob/84ca0d23ae52e4f0940f20b0e22eabe743f90dca/components/descriptions/index.tsx#L111C21-L111C56) | 3 | | × |
| ~~contentStyle~~ | Customize content style, Please use `styles.content` instead | CSSProperties | - | 4.10.0 | × |
| extra | The action area of the description list, placed at the top-right | ReactNode | - | 4.5.0 | × |
| items | Describe the contents of the list item | [DescriptionsItem](#descriptionitem)[] | - | 5.8.0 | × |
| ~~labelStyle~~ | Customize label style, Please use `styles.label` instead | CSSProperties | - | 4.10.0 | × |
| layout | Define description layout | `horizontal` \| `vertical` | `horizontal` | | × |
| size | Set the size of the list. Can be set to `medium`,`small`, or not filled | `large` \| `medium` \| `small` | `large` | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.23.0 |
| title | The title of the description list, placed at the top | ReactNode | - | | × |
### DescriptionItem
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| ~~contentStyle~~ | Customize content style, Please use `styles.content` instead | CSSProperties | - | 4.9.0 |
| label | The description of the content | ReactNode | - | |
| ~~labelStyle~~ | Customize label style, Please use `styles.label` instead | CSSProperties | - | 4.9.0 |
| span | The number of columns included(`filled` Fill the remaining part of the current row) | number \| `filled` \| [Screens](/components/grid#col) | 1 | `screens: 5.9.0`, `filled: 5.22.0` |
> The number of span Description.Item. Span={2} takes up the width of two DescriptionItems. When both `style` and `labelStyle`(or `contentStyle`) configured, both of them will work. And next one will overwrite first when conflict.
## Semantic DOM
https://ant.design/components/descriptions/semantic.md
## Design Token
## Component Token (Descriptions)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colonMarginLeft | Left margin of colon | number | 2 |
| colonMarginRight | Right margin of colon | number | 8 |
| contentColor | Text color of content | string | rgba(0,0,0,0.88) |
| extraColor | Text color of extra area | string | rgba(0,0,0,0.88) |
| itemPaddingBottom | Bottom padding of item | number | 16 |
| itemPaddingEnd | End padding of item | number | 16 |
| labelBg | Background color of label | string | rgba(0,0,0,0.02) |
| labelColor | Text color of label | string | rgba(0,0,0,0.45) |
| titleColor | Text color of title | string | rgba(0,0,0,0.88) |
| titleMarginBottom | Bottom margin of title | number | 20 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| colorSplit | Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextSecondary | The second level of text color is generally used in scenarios where text color is not emphasized, such as label text, menu text selection state, etc. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeLG | Large font size | number | |
| fontWeightStrong | Control the font weight of heading components (such as h1, h2, h3) or selected item. | number | |
| lineHeight | Line height of text. | number | |
| lineHeightLG | Line height of large text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| padding | Control the padding of the element. | number | |
| paddingLG | Control the large padding of the element. | number | |
| paddingSM | Control the small padding of the element. | number | |
| paddingXS | Control the extra small padding of the element. | number | |
---
## divider
Source: https://ant.design/components/divider.md
---
category: Components
title: Divider
description: A divider line separates different content.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*7sMiTbzvaDoAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*KPSEQ74PLg4AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group:
title: Layout
order: 2
---
## When To Use
- Divide sections of an article.
- Divide inline text and links such as the operation column of table.
## Examples
### Horizontal
A Divider is `horizontal` by default. You can add text within Divider.
```tsx
import React from 'react';
import { Divider } from 'antd';
const App: React.FC = () => (
<>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
>
);
export default App;
```
### Divider with title
Divider with inner title, set `titlePlacement="start/end"` to align it.
```tsx
import React from 'react';
import { Divider } from 'antd';
const App: React.FC = () => (
<>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Text
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Left Text
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Right Text
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Left Text margin with 0
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Right Text margin with 50px
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
>
);
export default App;
```
### Set the spacing size of the divider
The size of the spacing.
```tsx
import React from 'react';
import { Divider } from 'antd';
const App: React.FC = () => (
<>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
>
);
export default App;
```
### Text without heading style
You can use non-heading style of divider text by setting the `plain` property.
```tsx
import React from 'react';
import { Divider } from 'antd';
const App: React.FC = () => (
<>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Text
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Left Text
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Right Text
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
>
);
export default App;
```
### Vertical
Use `orientation="vertical"` or `vertical` to make the divider vertical.
```tsx
import React from 'react';
import { Divider } from 'antd';
const App: React.FC = () => (
<>
Text
Link
Link
>
);
export default App;
```
### Variant
Divider is of `solid` variant by default. You can change that to either `dashed` or `dotted`.
```tsx
import React from 'react';
import { Divider } from 'antd';
const App: React.FC = () => (
<>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Solid
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Dotted
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Dashed
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
>
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of divider by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Divider } from 'antd';
import type { DividerProps, GetProp } from 'antd';
const classNamesObject: DividerProps['classNames'] = {
root: 'demo-divider-root',
content: 'demo-divider-content',
rail: 'demo-divider-rail',
};
const classNamesFn: DividerProps['classNames'] = (
info,
): GetProp => {
if (info.props.titlePlacement === 'start') {
return {
root: 'demo-divider-root--start',
};
}
return {
root: 'demo-divider-root--default',
};
};
const stylesObject: DividerProps['styles'] = {
root: { borderWidth: 2, borderStyle: 'dashed' },
content: { fontStyle: 'italic' },
rail: { opacity: 0.85 },
};
const stylesFn: DividerProps['styles'] = (info): GetProp => {
if (info.props.size === 'small') {
return {
root: { opacity: 0.6, cursor: 'default' },
};
}
return {
root: { backgroundColor: '#fafafa', borderColor: '#d9d9d9' },
};
};
const App: React.FC = () => (
classNames Object
classNames Function
styles Object
styles Function
);
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| children | The wrapped title | ReactNode | - | | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| dashed | Whether line is dashed | boolean | false | | × |
| orientation | Whether line is horizontal or vertical | `horizontal` \| `vertical` | `horizontal` | - | × |
| ~~orientationMargin~~ | The margin-left/right between the title and its closest border, while the `titlePlacement` should not be `center`, If a numeric value of type `string` is provided without a unit, it is assumed to be in pixels (px) by default. | string \| number | - | | × |
| plain | Divider text show as plain style | boolean | false | 4.2.0 | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| size | The size of divider. Only valid for horizontal layout | `small` \| `medium` \| `large` | - | 5.25.0 | × |
| titlePlacement | The position of title inside divider | `start` \| `end` \| `center` | `center` | - | × |
| ~~type~~ | The direction type of divider | `horizontal` \| `vertical` | `horizontal` | - | × |
| variant | Whether line is dashed, dotted or solid | `dashed` \| `dotted` \| `solid` | solid | 5.20.0 | × |
| vertical | Orientation, Simultaneously configure with `orientation` and prioritize `orientation` | boolean | false | - | × |
## Semantic DOM
https://ant.design/components/divider/semantic.md
## Design Token
## Component Token (Divider)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| orientationMargin | Distance between text and edge, which should be a number between 0 and 1. | number | 0.05 |
| textPaddingInline | Horizontal padding of text | PaddingInline \| undefined | 1em |
| verticalMarginInline | Horizontal margin of vertical Divider | MarginInline \| undefined | 8 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorSplit | Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextHeading | Control the font color of heading. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeLG | Large font size | number | |
| lineHeight | Line height of text. | number | |
| lineWidth | Border width of base components | number | |
| margin | Control the margin of an element, with a medium size. | number | |
| marginLG | Control the margin of an element, with a large size. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
---
## drawer
Source: https://ant.design/components/drawer.md
---
group: Feedback
category: Components
title: Drawer
description: A panel that slides out from the edge of the screen.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*BD2JSKm8I-kAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*r29rQ51bNdwAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
A Drawer is a panel that is typically overlaid on top of a page and slides in from the side. It contains a set of information or actions. Since the user can interact with the Drawer without leaving the current page, tasks can be achieved more efficiently within the same context.
- Use a Form to create or edit a set of information.
- Processing subtasks. When subtasks are too heavy for a Popover and we still want to keep the subtasks in the context of the main task, Drawer comes very handy.
- When the same Form is needed in multiple places.
> Notes for developers
>
> Since the `5.17.0`, we provided the `loading` prop by the Spin. However, since the `5.18.0` version, we have fixed this design error and replaced the Spin with the Skeleton, and also modified the type of `loading` prop, which can only accept `boolean` type.
## Examples
### Basic
Basic drawer.
```tsx
import React, { useState } from 'react';
import { Button, Drawer } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
};
return (
<>
Open
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### Custom Placement
The Drawer can appear from any edge of the screen.
```tsx
import React, { useState } from 'react';
import type { DrawerProps, RadioChangeEvent } from 'antd';
import { Button, Drawer, Radio, Space } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [placement, setPlacement] = useState('left');
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
};
const onChange = (e: RadioChangeEvent) => {
setPlacement(e.target.value);
};
return (
<>
top
right
bottom
left
Open
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### Resizable
Resizable drawer that allows users to adjust the drawer's width or height by dragging the edge.
```tsx
import React, { useState } from 'react';
import type { DrawerProps, RadioChangeEvent } from 'antd';
import { Button, Drawer, Radio, Space } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [placement, setPlacement] = useState('right');
const [size, setSize] = useState(256);
const onChange = (e: RadioChangeEvent) => {
setSize(256);
setPlacement(e.target.value);
};
return (
<>
({
label: pos,
value: pos,
}))}
/>
setOpen(true)}>
Open Drawer
Current size: {size}px
setOpen(false)}
open={open}
key={placement}
size={size}
resizable={{
onResize: (newSize) => setSize(newSize),
}}
>
Drag the edge to resize the drawer
Current size: {size}px
>
);
};
export default App;
```
### Loading
Set the loading status of Drawer.
```tsx
import React from 'react';
import { Button, Drawer } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = React.useState(false);
const [loading, setLoading] = React.useState(true);
const showLoading = () => {
setOpen(true);
setLoading(true);
// Simple loading mock. You should add cleanup logic in real world.
setTimeout(() => {
setLoading(false);
}, 2000);
};
return (
<>
Open Drawer
Loading Drawer}
placement="right"
open={open}
loading={loading}
onClose={() => setOpen(false)}
>
Reload
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### Extra Actions
Extra actions should be placed at corner of drawer in Ant Design, you can use `extra` prop for that.
```tsx
import React, { useState } from 'react';
import { Button, Drawer, Radio, Space } from 'antd';
import type { DrawerProps, RadioChangeEvent } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [placement, setPlacement] = useState('right');
const showDrawer = () => {
setOpen(true);
};
const onChange = (e: RadioChangeEvent) => {
setPlacement(e.target.value);
};
const onClose = () => {
setOpen(false);
};
return (
<>
top
right
bottom
left
Open
Cancel
OK
}
>
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### Render in current dom
Render in current dom. custom container, check `getContainer`.
> Note: `style` and `className` props are moved to Drawer panel in v5 which is aligned with Modal component. Original `style` and `className` props are replaced by `rootStyle` and `rootClassName`.
> When `getContainer` returns a DOM node, you need to manually set `rootStyle` to `{ position: 'absolute' }`, see [#41951](https://github.com/ant-design/ant-design/issues/41951#issuecomment-1521099152).
```tsx
import React, { useState } from 'react';
import { Button, Drawer, theme } from 'antd';
const App: React.FC = () => {
const { token } = theme.useToken();
const [open, setOpen] = useState(false);
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
};
const containerStyle: React.CSSProperties = {
position: 'relative',
height: 200,
padding: 48,
overflow: 'hidden',
background: token.colorFillAlter,
border: `1px solid ${token.colorBorderSecondary}`,
borderRadius: token.borderRadiusLG,
};
return (
Render in this
Open
Some contents...
);
};
export default App;
```
### Submit form in drawer
Use a form in Drawer with a submit button.
```css
.site-form-in-drawer-wrapper {
position: absolute;
inset-inline-end: 0;
bottom: 0;
width: 100%;
padding: 10px 16px;
text-align: end;
background-color: #fff;
border-top: 1px solid #e9e9e9;
}
```
```tsx
import React, { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Col, DatePicker, Drawer, Form, Input, Row, Select, Space } from 'antd';
import type { InputProps } from 'antd';
const UrlInput: React.FC = (props) => {
return (
http://
.com
);
};
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
};
return (
<>
}>
New account
Cancel
Submit
}
>
>
);
};
export default App;
```
### Preview drawer
Use Drawer to quickly preview details of an object, such as those in a list.
```css
.site-description-item-profile-wrapper {
margin-bottom: 7px;
color: rgba(0, 0, 0, 0.65);
font-size: 14px;
line-height: 1.5715;
}
.ant-drawer-body p.site-description-item-profile-p {
display: block;
margin-bottom: 16px;
color: rgba(0, 0, 0, 0.85);
font-size: 16px;
line-height: 1.5715;
}
.site-description-item-profile-p-label {
display: inline-block;
margin-inline-end: 8px;
color: rgba(0, 0, 0, 0.85);
}
```
```tsx
import React, { useState } from 'react';
import { Avatar, Col, Divider, Drawer, List, Row } from 'antd';
interface DescriptionItemProps {
title: string;
content: React.ReactNode;
}
const DescriptionItem = ({ title, content }: DescriptionItemProps) => (
);
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
};
return (
<>
(
View Profile
,
]}
>
}
title={{item.name} }
description="Progresser XTech"
/>
)}
/>
User Profile
Personal
Company
Lin} />
Contacts
github.com/ant-design/ant-design
}
/>
>
);
};
export default App;
```
### Multi-level drawer
Open a new drawer on top of an existing drawer to handle multi branch tasks.
```tsx
import React, { useState } from 'react';
import { Button, Drawer } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [childrenDrawer, setChildrenDrawer] = useState(false);
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
};
const showChildrenDrawer = () => {
setChildrenDrawer(true);
};
const onChildrenDrawerClose = () => {
setChildrenDrawer(false);
};
return (
<>
Open drawer
Two-level drawer
This is two-level drawer
>
);
};
export default App;
```
### Preset size
The default width (or height) of Drawer is `378px`, and there is a preset large size `736px`.
```tsx
import React, { useState } from 'react';
import { Button, Drawer, Radio, Space } from 'antd';
import type { DrawerProps } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [size, setSize] = useState();
const onClose = () => {
setOpen(false);
};
return (
<>
setSize(e.target.value)}
options={[
{ label: 'Large Size (736px)', value: 'large' },
{ label: 'Default Size (378px)', value: 'default' },
{ label: 256, value: 256 },
{ label: '500px', value: '500px' },
{ label: '50%', value: '50%' },
{ label: '20vw', value: '20vw' },
]}
/>
setOpen(true)}>
Open Drawer
Cancel
OK
}
>
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### mask
mask effect.
```tsx
import React, { useState } from 'react';
import { Button, Drawer, Space } from 'antd';
type MaskType = 'blur' | 'dimmed' | 'none';
type DrawerConfig = {
type: MaskType;
mask: boolean | { blur: boolean };
title: string;
};
const drawerList: DrawerConfig[] = [
{ type: 'blur', mask: { blur: true }, title: 'blur' },
{ type: 'dimmed', mask: true, title: 'Dimmed mask' },
{ type: 'none', mask: false, title: 'No mask' },
];
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showDrawer = (type: MaskType) => {
setOpen(type);
};
const onClose = () => {
setOpen(false);
};
return (
{drawerList.map((item) => (
{
showDrawer(item.type);
}}
>
{item.title}
Some contents...
Some contents...
Some contents...
))}
);
};
export default App;
```
### Closable placement
Drawer with closable placement, customize the close placement to the `end`, defaults to `start`.
```tsx
import React, { useState } from 'react';
import { Button, Drawer } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
};
return (
<>
Open
Some contents...
Some contents...
Take a look at the top-right corner...
>
);
};
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Drawer by passing objects or functions through `classNames` and `styles`.
```tsx
import React, { useState } from 'react';
import { Button, Drawer, Flex } from 'antd';
import type { DrawerProps, GetProp } from 'antd';
import { createStaticStyles } from 'antd-style';
const lineStyle: React.CSSProperties = {
lineHeight: '28px',
};
const sharedContent = (
<>
Following the Ant Design specification, we developed a React UI library antd that contains a
set of high quality components and demos for building rich, interactive user interfaces.
🌈 Enterprise-class UI designed for web applications.
📦 A set of high-quality React components out of the box.
🛡 Written in TypeScript with predictable static types.
⚙️ Whole package of design resources and development tools.
🌍 Internationalization support for dozens of languages.
🎨 Powerful theme customization in every detail.
>
);
const classNames = createStaticStyles(
({ css }): NonNullable> => ({
root: css`
border-radius: 10px;
padding: 10px;
`,
}),
);
const styles: DrawerProps['styles'] = {
mask: {
backgroundImage: `linear-gradient(to top, #18181b 0, rgba(21, 21, 22, 0.2) 100%)`,
},
};
const stylesFn: DrawerProps['styles'] = (info): GetProp => {
if (info.props.footer) {
return {
header: {
padding: 16,
},
body: {
padding: 16,
},
footer: {
padding: '16px 10px',
backgroundColor: '#fafafa',
},
};
}
};
const App: React.FC = () => {
const [drawerOpen, setDrawerOpen] = useState(false);
const [drawerFnOpen, setDrawerFnOpen] = useState(false);
const sharedProps: DrawerProps = {
classNames,
size: 500,
};
const footer: React.ReactNode = (
setDrawerFnOpen(false)}
styles={{ root: { borderColor: '#ccc', color: '#171717', backgroundColor: '#fff' } }}
>
Cancel
setDrawerOpen(true)}
>
Submit
);
return (
setDrawerOpen(true)}>Open Style Drawer
setDrawerFnOpen(true)}>
Open Function Drawer
setDrawerOpen(false)}
>
{sharedContent}
setDrawerFnOpen(false)}
>
{sharedContent}
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| afterOpenChange | Callback after the animation ends when switching drawers | function(open) | - | | × |
| ~~bodyStyle~~ | Style of the drawer body, please use `styles.body` instead | CSSProperties | - | - | × |
| className | Config Drawer Panel className. Use `rootClassName` if want to config top DOM style | string | - | | 5.7.0 |
| classNames | Customize class for each semantic structure inside the Drawer component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.10.0 |
| closable | Whether to show a close button. The position can be configured with `placement` | boolean \| { closeIcon?: React.ReactNode; disabled?: boolean; placement?: 'start' \| 'end' } | true | placement: 5.28.0 | 5.15.0, placement: 6.1.1 |
| ~~contentWrapperStyle~~ | Style of the drawer wrapper, please use `styles.wrapper` instead | CSSProperties | - | - | × |
| ~~destroyOnClose~~ | Whether to unmount child components on closing drawer or not | boolean | false | | × |
| ~~destroyInactivePanel~~ | Whether to unmount child components on closing drawer or not, please use `destroyOnHidden` instead | boolean | false | - | × |
| destroyOnHidden | Whether to unmount child components on closing drawer or not | boolean | false | 5.25.0 | × |
| ~~drawerStyle~~ | Style of the drawer panel, please use `styles.section` instead | CSSProperties | - | - | × |
| extra | Extra actions area at corner | ReactNode | - | 4.17.0 | × |
| footer | The footer for Drawer | ReactNode | - | | × |
| ~~footerStyle~~ | Style of the drawer footer, please use `styles.footer` instead | CSSProperties | - | - | × |
| forceRender | Pre-render Drawer component forcibly | boolean | false | | × |
| focusable | Configuration for focus management in the Drawer | `{ trap?: boolean, focusTriggerAfterClose?: boolean }` | - | 6.2.0 | 6.4.0 |
| getContainer | mounted node and display window for Drawer | HTMLElement \| () => HTMLElement \| Selectors \| false | body | | × |
| ~~headerStyle~~ | Style of the drawer header part, please use `styles.header` instead | CSSProperties | - | | × |
| ~~height~~ | Placement is `top` or `bottom`, height of the Drawer dialog, please use `size` instead | string \| number | 378 | | × |
| keyboard | Whether support press esc to close | boolean | true | | × |
| loading | Show the Skeleton | boolean | false | 5.17.0 | × |
| mask | Mask effect | boolean \| `{ enabled?: boolean, blur?: boolean, closable?: boolean }` | true | mask.closable: 6.3.0 | 6.0.0, mask.closable: 6.3.0 |
| ~~maskClosable~~ | Clicking on the mask (area outside the Drawer) to close the Drawer or not | boolean | true | | × |
| ~~maskStyle~~ | Style of the drawer mask, please use `styles.mask` instead | CSSProperties | - | - | × |
| maxSize | Maximum size (width or height depending on `placement`) when resizable | number | - | 6.0.0 | × |
| open | Whether the Drawer dialog is visible or not | boolean | false | | × |
| placement | The placement of the Drawer | `top` \| `right` \| `bottom` \| `left` | `right` | | × |
| push | Nested drawers push behavior | boolean \| { distance: string \| number } | { distance: 180 } | 4.5.0+ | × |
| resizable | Enable resizable by dragging | boolean \| [ResizableConfig](#resizableconfig) | - | boolean: 6.1.0 | × |
| rootStyle | Style of wrapper element which **contains mask** compare to `style` | CSSProperties | - | | × |
| size | preset size of drawer, default `378px` and large `736px`, or a custom number | 'default' \| 'large' \| number \| string | 'default' | 4.17.0, string: 6.2.0 | × |
| style | Style of Drawer panel. Use `styles.body` if want to config body only | CSSProperties | - | | 5.7.0 |
| styles | Customize inline style for each semantic structure inside the Drawer component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.10.0 |
| title | The title for Drawer | ReactNode | - | | × |
| ~~width~~ | Width of the Drawer dialog, please use `size` instead | string \| number | 378 | | × |
| zIndex | The `z-index` of the Drawer | number | 1000 | | × |
| onClose | Specify a callback that will be called when a user clicks mask, close button or Cancel button | function(e) | - | | × |
| drawerRender | Custom drawer content render | (node: ReactNode) => ReactNode | - | 5.18.0 | × |
### ResizableConfig
| Property | Description | Type | Default | Version |
| ------------- | --------------------------- | ---------------------- | ------- | ------- |
| onResizeStart | Callback when resize starts | () => void | - | 6.0.0 |
| onResize | Callback during resizing | (size: number) => void | - | 6.0.0 |
| onResizeEnd | Callback when resize ends | () => void | - | 6.0.0 |
## Semantic DOM
https://ant.design/components/drawer/semantic.md
## Design Token
## Component Token (Drawer)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| draggerSize | Size of resize handle | number | 4 |
| footerPaddingBlock | Vertical padding of footer | number | 8 |
| footerPaddingInline | Horizontal padding of footer | number | 16 |
| zIndexPopup | z-index of drawer | number | 1000 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| colorBgElevated | Container background color of the popup layer, in dark mode the color value of this token will be a little brighter than `colorBgContainer`. E.g: modal, pop-up, menu, etc. | string | |
| colorBgMask | The background color of the mask, used to cover the content below the mask, Modal, Drawer, Image and other components use this token | string | |
| colorBgTextActive | Control the background color of text in active state. | string | |
| colorBgTextHover | Control the background color of text in hover state. | string | |
| colorIcon | Weak action. Such as `allowClear` or Alert close button | string | |
| colorIconHover | Weak action hover color. Such as `allowClear` or Alert close button | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorSplit | Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| fontSizeLG | Large font size | number | |
| fontWeightStrong | Control the font weight of heading components (such as h1, h2, h3) or selected item. | number | |
| lineHeightLG | Line height of large text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| padding | Control the padding of the element. | number | |
| paddingLG | Control the large padding of the element. | number | |
| paddingXS | Control the extra small padding of the element. | number | |
---
## dropdown
Source: https://ant.design/components/dropdown.md
---
category: Components
group: Navigation
title: Dropdown
description: A dropdown list.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*gTBySYX11WcAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*k619RJ_7bKEAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
When there are more than a few options to choose from, you can wrap them in a `Dropdown`. By hovering or clicking on the trigger, a dropdown menu will appear, which allows you to choose an option and execute the relevant action.
## Examples
### Basic
The most basic dropdown menu.
```tsx
import React from 'react';
import { DownOutlined, SmileOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
key: '1',
label: (
1st menu item
),
},
{
key: '2',
label: (
2nd menu item (disabled)
),
icon: ,
disabled: true,
},
{
key: '3',
label: (
3rd menu item (disabled)
),
disabled: true,
},
{
key: '4',
danger: true,
label: 'a danger item',
},
];
const App: React.FC = () => (
e.preventDefault()}>
Hover me
);
export default App;
```
### Extra node
The dropdown menu with shortcut.
```tsx
import React from 'react';
import { DownOutlined, SettingOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
key: '1',
label: 'My Account',
disabled: true,
},
{
type: 'divider',
},
{
key: '2',
label: 'Profile',
extra: '⌘P',
},
{
key: '3',
label: 'Billing',
extra: '⌘B',
},
{
key: '4',
label: 'Settings',
icon: ,
extra: '⌘S',
},
];
const App: React.FC = () => (
e.preventDefault()}>
Hover me
);
export default App;
```
### Placement
Support 6 placements.
```tsx
import React from 'react';
import type { MenuProps } from 'antd';
import { Button, Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
key: '1',
label: (
1st menu item
),
},
{
key: '2',
label: (
2nd menu item
),
},
{
key: '3',
label: (
3rd menu item
),
},
];
const App: React.FC = () => (
bottomLeft
bottom
bottomRight
topLeft
top
topRight
);
export default App;
```
### Arrow
You could display an arrow.
```tsx
import React from 'react';
import type { MenuProps } from 'antd';
import { Button, Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
key: '1',
label: (
1st menu item
),
},
{
key: '2',
label: (
2nd menu item
),
},
{
key: '3',
label: (
3rd menu item
),
},
];
const App: React.FC = () => (
bottomLeft
bottom
bottomRight
topLeft
top
topRight
);
export default App;
```
### Other elements
Divider and disabled menu item.
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
label: (
1st menu item
),
key: '0',
},
{
label: (
2nd menu item
),
key: '1',
},
{
type: 'divider',
},
{
label: '3rd menu item(disabled)',
key: '3',
disabled: true,
},
];
const App: React.FC = () => (
e.preventDefault()}>
Hover me
);
export default App;
```
### Arrow pointing at the center
By specifying `arrow` prop with `{ pointAtCenter: true }`, the arrow will point to the center of the target element.
```tsx
import React from 'react';
import type { MenuProps } from 'antd';
import { Button, Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
key: '1',
label: (
1st menu item
),
},
{
key: '2',
label: (
2nd menu item
),
},
{
key: '3',
label: (
3rd menu item
),
},
];
const App: React.FC = () => (
bottomLeft
bottom
bottomRight
topLeft
top
topRight
);
export default App;
```
### Trigger mode
The default trigger mode is `hover`, you can change it to `click`.
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
label: (
1st menu item
),
key: '0',
},
{
label: (
2nd menu item
),
key: '1',
},
{
type: 'divider',
},
{
label: '3rd menu item',
key: '3',
},
];
const App: React.FC = () => (
e.preventDefault()}>
Click me
);
export default App;
```
### Click event
An event will be triggered when you click menu items, in which you can make different operations according to item's key.
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, message, Space } from 'antd';
const items: MenuProps['items'] = [
{
label: '1st menu item',
key: '1',
},
{
label: '2nd menu item',
key: '2',
},
{
label: '3rd menu item',
key: '3',
},
];
const App: React.FC = () => {
const [messageApi, contextHolder] = message.useMessage();
const onClick: MenuProps['onClick'] = ({ key }) => {
messageApi.info(`Click on item ${key}`);
};
return (
<>
{contextHolder}
e.preventDefault()}>
Hover me, Click menu item
>
);
};
export default App;
```
### Button with dropdown menu
A button is on the left, and a related functional menu is on the right. You can set the icon property to modify the icon of right.
```tsx
import React from 'react';
import { DownOutlined, EllipsisOutlined, UserOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Button, Dropdown, message, Space, Tooltip } from 'antd';
const items: MenuProps['items'] = [
{
label: '1st menu item',
key: '1',
icon: ,
},
{
label: '2nd menu item',
key: '2',
icon: ,
},
{
label: '3rd menu item',
key: '3',
icon: ,
danger: true,
},
{
label: '4rd menu item',
key: '4',
icon: ,
danger: true,
disabled: true,
},
];
const App: React.FC = () => {
const [messageApi, contextHolder] = message.useMessage();
const handleButtonClick = (e: React.MouseEvent) => {
messageApi.info('Click on left button.');
console.log('click left button', e);
};
const handleMenuClick: MenuProps['onClick'] = (e) => {
messageApi.info('Click on menu item.');
console.log('click', e);
};
const menuProps = {
items,
onClick: handleMenuClick,
};
return (
<>
{contextHolder}
Dropdown
} />
Dropdown
} />
Dropdown
} disabled />
With Tooltip
} iconPlacement="end">
Button
Danger
} danger />
>
);
};
export default App;
```
### Custom dropdown
Customize the dropdown menu via `popupRender`. If you don't need the Menu content, use the Popover component directly.
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import { Button, Divider, Dropdown, Space, theme } from 'antd';
import type { MenuProps } from 'antd';
const { useToken } = theme;
const items: MenuProps['items'] = [
{
key: '1',
label: (
1st menu item
),
},
{
key: '2',
label: (
2nd menu item (disabled)
),
disabled: true,
},
{
key: '3',
label: (
3rd menu item (disabled)
),
disabled: true,
},
];
const App: React.FC = () => {
const { token } = useToken();
const contentStyle: React.CSSProperties = {
backgroundColor: token.colorBgElevated,
borderRadius: token.borderRadiusLG,
boxShadow: token.boxShadowSecondary,
};
const menuStyle: React.CSSProperties = {
boxShadow: 'none',
};
return (
(
{React.cloneElement(
menu as React.ReactElement<{
style: React.CSSProperties;
}>,
{ style: menuStyle },
)}
Click me!
)}
>
e.preventDefault()}>
Hover me
);
};
export default App;
```
### Cascading menu
The menu has multiple levels.
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
key: '1',
type: 'group',
label: 'Group title',
children: [
{
key: '1-1',
label: '1st menu item',
},
{
key: '1-2',
label: '2nd menu item',
},
],
},
{
key: '2',
label: 'sub menu',
children: [
{
key: '2-1',
label: '3rd menu item',
},
{
key: '2-2',
label: '4th menu item',
},
],
},
{
key: '3',
label: 'disabled sub menu',
disabled: true,
children: [
{
key: '3-1',
label: '5d menu item',
},
{
key: '3-2',
label: '6th menu item',
},
],
},
];
const App: React.FC = () => (
e.preventDefault()}>
Cascading menu
);
export default App;
```
### The way of hiding menu.
The default is to close the menu when you click on menu items, this feature can be turned off.
```tsx
import React, { useState } from 'react';
import { DownOutlined } from '@ant-design/icons';
import type { DropdownProps, MenuProps } from 'antd';
import { Dropdown, Space } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const handleMenuClick: MenuProps['onClick'] = (e) => {
if (e.key === '3') {
setOpen(false);
}
};
const handleOpenChange: DropdownProps['onOpenChange'] = (nextOpen, info) => {
if (info.source === 'trigger' || nextOpen) {
setOpen(nextOpen);
}
};
const items: MenuProps['items'] = [
{
label: 'Clicking me will not close the menu.',
key: '1',
},
{
label: 'Clicking me will not close the menu also.',
key: '2',
},
{
label: 'Clicking me will close the menu.',
key: '3',
},
];
return (
e.preventDefault()}>
Hover me
);
};
export default App;
```
### Context Menu
The default trigger mode is `hover`, you can change it to `contextMenu`. The pop-up menu position will follow the right-click position.
```tsx
import React from 'react';
import type { MenuProps } from 'antd';
import { Dropdown, theme } from 'antd';
const items: MenuProps['items'] = [
{
label: '1st menu item',
key: '1',
},
{
label: '2nd menu item',
key: '2',
},
{
label: '3rd menu item',
key: '3',
},
];
const App: React.FC = () => {
const {
token: { colorBgLayout, colorTextTertiary },
} = theme.useToken();
return (
Right Click on here
);
};
export default App;
```
### Loading
A loading indicator can be added to a button by setting the `loading` property.
```tsx
import React, { useState } from 'react';
import { DownOutlined, EllipsisOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Button, Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
label: 'Submit and continue',
key: '1',
},
];
const App: React.FC = () => {
const [loadings, setLoadings] = useState([]);
const enterLoading = (index: number) => {
setLoadings((state) => {
const newLoadings = [...state];
newLoadings[index] = true;
return newLoadings;
});
setTimeout(() => {
setLoadings((state) => {
const newLoadings = [...state];
newLoadings[index] = false;
return newLoadings;
});
}, 6000);
};
return (
Submit
} />
Submit
} />
enterLoading(0)}>
Submit
} />
enterLoading(1)}>
Submit
} />
);
};
export default App;
```
### Selectable Menu
Configure the `selectable` property in `menu` to enable selectable ability.
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space, Typography } from 'antd';
const items: MenuProps['items'] = [
{
key: '1',
label: 'Item 1',
},
{
key: '2',
label: 'Item 2',
},
{
key: '3',
label: 'Item 3',
},
];
const App: React.FC = () => (
Selectable
);
export default App;
```
### Selection actions
Use `Dropdown` with the browser Selection API to show custom actions after selecting text.
```tsx
import React, { useRef, useState } from 'react';
import type { MenuProps } from 'antd';
import { Dropdown, message } from 'antd';
import { createStyles } from 'antd-style';
import type { ItemType } from 'antd/es/menu/interface';
interface SelectionInfo {
text: string;
x: number;
y: number;
}
const labels: Record = {
mask: 'Mask keyword',
mark: 'Mark keyword',
search: 'Search keyword',
};
const useStyle = createStyles(({ cssVar, css }) => {
const { colorText, colorBgLayout, borderRadiusLG, paddingLG } = cssVar;
return {
wrapper: css`
padding: ${paddingLG};
user-select: text;
color: ${colorText};
background-color: ${colorBgLayout};
border-radius: ${borderRadiusLG};
`,
trigger: css`
position: fixed;
display: block;
width: 1px;
height: 1px;
margin: 0;
padding: 0;
pointer-events: none;
`,
};
});
const items = Object.entries(labels).map(([key, label]) => ({ key, label }));
const Demo: React.FC = () => {
const [messageApi, contextHolder] = message.useMessage();
const { styles } = useStyle();
const wrapperRef = useRef(null);
const [selection, setSelection] = useState(null);
const handleSelect = () => {
const selectionInstance = window.getSelection();
const selectedText = selectionInstance?.toString().trim();
if (!selectionInstance || !selectedText || selectionInstance.rangeCount === 0) {
setSelection(null);
return;
}
const range = selectionInstance.getRangeAt(0);
if (!wrapperRef.current?.contains(range.commonAncestorContainer)) {
setSelection(null);
return;
}
const rect = range.getBoundingClientRect();
if (!rect.width || !rect.height) {
setSelection(null);
return;
}
setSelection({
text: selectedText,
x: rect.left + rect.width / 2,
y: rect.bottom + 4,
});
};
const handleMouseUp: React.MouseEventHandler = () => {
setTimeout(handleSelect);
};
const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
if (!selection) {
return;
}
messageApi.info(`${labels[key]}: ${selection.text}`);
window.getSelection()?.removeAllRanges();
setSelection(null);
};
return (
<>
{contextHolder}
{
if (!nextOpen) {
setSelection(null);
}
}}
>
setSelection(null)}
onMouseUp={handleMouseUp}
className={styles.wrapper}
>
Select any text in this paragraph to open a Dropdown menu near the selection. This is useful
for actions such as masking sensitive words, marking entities, or searching the selected
keyword. Example data: Alice, phone 13800138000, ID 110101199001011234.
>
);
};
export default Demo;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of the Dropdown by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { DownOutlined, LogoutOutlined, SettingOutlined } from '@ant-design/icons';
import { Button, Dropdown, Flex, Space } from 'antd';
import type { DropdownProps, GetProp, MenuProps } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
root: {
backgroundColor: token.colorFillAlter,
border: `1px solid ${token.colorBorder}`,
borderRadius: token.borderRadius,
},
}));
const items: MenuProps['items'] = [
{
key: '1',
label: 'Profile',
},
{
key: '2',
label: 'Settings',
icon: ,
},
{
type: 'divider',
},
{
key: '3',
label: 'Logout',
icon: ,
danger: true,
},
];
const objectStyles: DropdownProps['styles'] = {
root: {
backgroundColor: '#fff',
border: '1px solid #d9d9d9',
borderRadius: '4px',
},
item: {
padding: '8px 12px',
fontSize: '14px',
},
itemTitle: {
fontWeight: '500',
},
itemIcon: {
color: '#1890ff',
marginInlineEnd: '8px',
},
itemContent: {
backgroundColor: 'transparent',
},
};
const functionStyles: DropdownProps['styles'] = (
info,
): GetProp => {
const { props } = info;
const isClick = props.trigger?.includes('click');
if (isClick) {
return {
root: {
borderColor: '#1890ff',
borderRadius: '8px',
},
};
}
return {};
};
const App: React.FC = () => {
const { styles } = useStyles();
const sharedProps: DropdownProps = {
menu: { items },
placement: 'bottomLeft',
classNames: { root: styles.root },
};
return (
Object Style
Function Style
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Dropdown
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| arrow | Whether the dropdown arrow should be visible | boolean \| { pointAtCenter: boolean } | false | | × |
| autoAdjustOverflow | Whether to adjust dropdown placement automatically when dropdown is off screen | boolean | true | 5.2.0 | × |
| classNames | Customize class for each semantic structure inside the Dropdown component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| disabled | Whether the dropdown menu is disabled | boolean | - | | × |
| ~~destroyPopupOnHide~~ | Whether destroy dropdown when hidden, use `destroyOnHidden` instead | boolean | false | | × |
| destroyOnHidden | Whether destroy dropdown when hidden | boolean | false | 5.25.0 | × |
| ~~dropdownRender~~ | Customize dropdown content, use `popupRender` instead | (menus: ReactNode) => ReactNode | - | 4.24.0 | × |
| popupRender | Customize popup content | (menus: ReactNode) => ReactNode | - | 5.25.0 | × |
| getPopupContainer | To set the container of the dropdown menu. The default is to create a div element in body, but you can reset it to the scrolling area and make a relative reposition. [Example on CodePen](https://codepen.io/afc163/pen/zEjNOy?editors=0010) | (triggerNode: HTMLElement) => HTMLElement | () => document.body | | × |
| menu | The menu props | [MenuProps](/components/menu/#api) | - | | × |
| ~~overlayClassName~~ | The class name of the dropdown root element, please use `classNames.root` instead | string | - | | × |
| ~~overlayStyle~~ | The style of the dropdown root element, please use `styles.root` instead | CSSProperties | - | | × |
| placement | Placement of popup menu: `bottom` `bottomLeft` `bottomRight` `top` `topLeft` `topRight` | string | `bottomLeft` | | × |
| styles | Customize inline style for each semantic structure inside the Dropdown component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| trigger | The trigger mode which executes the dropdown action. Note that hover can't be used on touchscreens | Array<`click`\|`hover`\|`contextMenu`> | \[`hover`] | | × |
| open | Whether the dropdown menu is currently open | boolean | - | | × |
| onOpenChange | Called when the open state is changed. Not trigger when hidden by click item | (open: boolean, info: { source: 'trigger' \| 'menu' }) => void | - | `info.source`: 5.11.0 | × |
## Note
Please ensure that the child node of `Dropdown` accepts `onMouseEnter`, `onMouseLeave`, `onFocus`, `onClick` events.
## Semantic DOM
https://ant.design/components/dropdown/semantic.md
## Design Token
## Component Token (Dropdown)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| paddingBlock | Vertical padding of dropdown | PaddingBlock \| undefined | 5 |
| zIndexPopup | z-index of dropdown | number | 1050 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| borderRadiusXS | XS size border radius, used in some small border radius components, such as Segmented, Arrow and other components with small border radius. | number | |
| boxShadowSecondary | Control the secondary box shadow style of an element. | string | |
| colorBgElevated | Container background color of the popup layer, in dark mode the color value of this token will be a little brighter than `colorBgContainer`. E.g: modal, pop-up, menu, etc. | string | |
| colorError | Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. | string | |
| colorIcon | Weak action. Such as `allowClear` or Alert close button | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorSplit | Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDescription | Control the font color of text description. | string | |
| colorTextDisabled | Control the color of text in disabled state. | string | |
| colorTextLightSolid | Control the highlight color of text with background color, such as the text in Primary Button components. | string | |
| controlHeightLG | LG component height | number | |
| controlItemBgActive | Control the background color of control component item when active. | string | |
| controlItemBgActiveHover | Control the background color of control component item when hovering and active. | string | |
| controlItemBgHover | Control the background color of control component item when hovering. | string | |
| controlPaddingHorizontal | Control the horizontal padding of an element. | number | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeIcon | Control the font size of operation icon in Select, Cascader, etc. Normally same as fontSizeSM. | number | |
| fontSizeSM | Small font size | number | |
| lineHeight | Line height of text. | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionEaseInOutCirc | Preset motion curve. | string | |
| motionEaseInQuint | Preset motion curve. | string | |
| motionEaseOutCirc | Preset motion curve. | string | |
| motionEaseOutQuint | Preset motion curve. | string | |
| padding | Control the padding of the element. | number | |
| paddingXS | Control the extra small padding of the element. | number | |
| paddingXXS | Control the extra extra small padding of the element. | number | |
| sizePopupArrow | The size of the component arrow | number | |
## FAQ
### How to prevent Dropdown from being squeezed when it exceeds the screen horizontally? {#faq-dropdown-squeezed}
You can use `width: max-content` style to handle this. ref [#43025](https://github.com/ant-design/ant-design/issues/43025#issuecomment-1594394135).
---
## empty
Source: https://ant.design/components/empty.md
---
category: Components
group: Data Display
title: Empty
description: Empty state placeholder.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*ZdiZSLzEV0wAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*obM7S5lIxeMAAAAAAAAAAAAADrJ8AQ/original
---
## When To Use
- When there is no data provided, display for friendly tips.
- User tutorial to create something in fresh new situation.
## Examples
### Basic
Simplest Usage.
```tsx
import React from 'react';
import { Empty } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Choose image
You can choose another style of `image` by setting image to `Empty.PRESENTED_IMAGE_SIMPLE`.
```tsx
import React from 'react';
import { Empty } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Customize
Customize image source, image size, description and extra content.
```tsx
import React from 'react';
import { Button, Empty, Typography } from 'antd';
const App: React.FC = () => (
Customize Description
}
>
Create Now
);
export default App;
```
### ConfigProvider
Use ConfigProvider set global Empty style.
```tsx
import React, { useState } from 'react';
import { SmileOutlined } from '@ant-design/icons';
import {
Cascader,
ConfigProvider,
Divider,
List,
Select,
Space,
Switch,
Table,
Transfer,
TreeSelect,
} from 'antd';
const customizeRenderEmpty = () => (
);
const style: React.CSSProperties = { width: 200 };
const App: React.FC = () => {
const [customize, setCustomize] = useState(true);
return (
<>
Select
TreeSelect
Cascader
Transfer
Table
List
>
);
};
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Empty by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import type { EmptyProps, GetProp } from 'antd';
import { Button, Empty, Flex } from 'antd';
import { createStaticStyles } from 'antd-style';
const emptySharedProps: EmptyProps = {
image: Empty.PRESENTED_IMAGE_SIMPLE,
children: Create Now ,
};
const classNames = createStaticStyles(({ css }) => ({
root: css`
border: 1px dashed #ccc;
padding: 16px;
`,
}));
const stylesObject: EmptyProps['styles'] = {
root: { backgroundColor: '#f5f5f5', borderRadius: '8px' },
image: { filter: 'grayscale(100%)' },
description: { color: '#1890ff', fontWeight: 'bold' },
footer: { marginTop: '16px' },
};
const stylesFn: EmptyProps['styles'] = ({ props }): GetProp => {
if (props.description) {
return {
root: { backgroundColor: '#e6f7ff', border: '1px solid #91d5ff' },
description: { color: '#1890ff', fontWeight: 'bold' },
image: { filter: 'hue-rotate(180deg)' },
};
}
return {};
};
const App: React.FC = () => {
const emptyClassNames: EmptyProps['classNames'] = {
root: classNames.root,
};
return (
);
};
export default App;
```
### No description
Simplest Usage with no description.
```tsx
import React from 'react';
import { Empty } from 'antd';
const App: React.FC = () => ;
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
```jsx
Create
```
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.23.0 |
| description | Customize description | ReactNode | - | | × |
| image | Customize image. Will treat as image url when string provided | ReactNode | `Empty.PRESENTED_IMAGE_DEFAULT` | | 5.27.0 |
| ~~imageStyle~~ | The style of image, please use `styles.image` instead | CSSProperties | - | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.23.0 |
## Built-in images
- Empty.PRESENTED_IMAGE_SIMPLE
- Empty.PRESENTED_IMAGE_DEFAULT
## Semantic DOM
https://ant.design/components/empty/semantic.md
## Design Token
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorTextDescription | Control the font color of text description. | string | |
| controlHeightLG | LG component height | number | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| lineHeight | Line height of text. | number | |
| margin | Control the margin of an element, with a medium size. | number | |
| marginXL | Control the margin of an element, with an extra-large size. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| opacityImage | Control image opacity | number | |
---
## flex
Source: https://ant.design/components/flex.md
---
category: Components
group: Layout
title: Flex
description: A flex layout container for alignment.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*SMzgSJZE_AwAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*8yArQ43EGccAAAAAAAAAAAAADrJ8AQ/original
---
## When To Use
- Good for setting spacing between elements.
- Suitable for setting various horizontal and vertical alignments.
### Difference with Space component
- Space is used to set the spacing between inline elements. It will add a wrapper element for each child element for inline alignment. Suitable for equidistant arrangement of multiple child elements in rows and columns.
- Flex is used to set the layout of block-level elements. It does not add a wrapper element. Suitable for layout of child elements in vertical or horizontal direction, and provides more flexibility and control.
## Examples
### Basic
The basic usage.
```tsx
/* eslint-disable react/no-array-index-key */
import React from 'react';
import { Flex, Radio } from 'antd';
const baseStyle: React.CSSProperties = {
width: '25%',
height: 54,
};
const App: React.FC = () => {
const [value, setValue] = React.useState
('horizontal');
return (
setValue(e.target.value)}>
horizontal
vertical
{Array.from({ length: 4 }).map((_, i) => (
))}
);
};
export default App;
```
### align
Set align.
```tsx
import React from 'react';
import { Button, Flex, Segmented } from 'antd';
import type { FlexProps } from 'antd';
const boxStyle: React.CSSProperties = {
width: '100%',
height: 120,
borderRadius: 6,
border: '1px solid #40a9ff',
};
const justifyOptions = [
'flex-start',
'center',
'flex-end',
'space-between',
'space-around',
'space-evenly',
];
const alignOptions = ['flex-start', 'center', 'flex-end'];
const App: React.FC = () => {
const [justify, setJustify] = React.useState(justifyOptions[0]);
const [alignItems, setAlignItems] = React.useState(alignOptions[0]);
return (
Select justify :
Select align :
Primary
Primary
Primary
Primary
);
};
export default App;
```
### gap
Set the `gap` between elements, which has three preset sizes: `small`, `medium`, and `large`. You can also customize the gap size.
```tsx
import React from 'react';
import { Button, Flex, Radio, Slider } from 'antd';
import type { FlexProps } from 'antd';
const App: React.FC = () => {
const [gapSize, setGapSize] = React.useState('small');
const [customGapSize, setCustomGapSize] = React.useState(0);
return (
setGapSize(e.target.value)}>
{['small', 'medium', 'large', 'customize'].map((size) => (
{size}
))}
{gapSize === 'customize' && }
Primary
Default
Dashed
Link
);
};
export default App;
```
### Wrap
Auto wrap line.
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
const Demo: React.FC = () => (
{Array.from({ length: 24 }, (_, i) => (
Button
))}
);
export default Demo;
```
### combination
Nesting can achieve more complex layouts.
```tsx
import React from 'react';
import { Button, Card, Flex, Typography } from 'antd';
const cardStyle: React.CSSProperties = {
width: 620,
};
const imgStyle: React.CSSProperties = {
display: 'block',
width: 273,
};
const App: React.FC = () => (
“antd is an enterprise-class UI design language and React UI library.”
Get Started
);
export default App;
```
## API
> This component is available since `antd@5.10.0`. The default behavior of Flex in horizontal mode is to align upward, In vertical mode, aligns the stretch, You can adjust this via properties.
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| vertical | Is direction of the flex vertical, use `flex-direction: column` | boolean | false | 5.10.0 | 5.10.0 |
| wrap | Set whether the element is displayed in a single line or in multiple lines | [flex-wrap](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap) \| boolean | nowrap | boolean: 5.17.0 | × |
| justify | Sets the alignment of elements in the direction of the main axis | [justify-content](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content) | normal | | × |
| align | Sets the alignment of elements in the direction of the cross axis | [align-items](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items) | normal | | × |
| flex | flex CSS shorthand properties | [flex](https://developer.mozilla.org/en-US/docs/Web/CSS/flex) | normal | | × |
| gap | Sets the gap between grids | `small` \| `medium` \| `large` \| string \| number | - | | × |
| component | custom element type | React.ComponentType | `div` | | × |
| orientation | direction of the flex | `horizontal` \| `vertical` | `horizontal` | - | × |
## Design Token
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| padding | Control the padding of the element. | number | |
| paddingLG | Control the large padding of the element. | number | |
| paddingXS | Control the extra small padding of the element. | number | |
---
## float-button
Source: https://ant.design/components/float-button.md
---
category: Components
group: General
title: FloatButton
description: A button that floats at the top of the page.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*tXAoQqyr-ioAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*hSAwR7cnabwAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
- For global functionality on the site.
- Buttons that can be seen wherever you browse.
## Examples
### Basic
The most basic usage.
```tsx
import React from 'react';
import { FloatButton } from 'antd';
const App: React.FC = () => console.log('onClick')} />;
export default App;
```
### Type
Change the type of the FloatButton with the `type` property.
```tsx
import React from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
const App: React.FC = () => (
<>
} type="primary" style={{ insetInlineEnd: 24 }} />
} type="default" style={{ insetInlineEnd: 94 }} />
>
);
export default App;
```
### Shape
Change the shape of the FloatButton with the `shape` property.
```tsx
import React from 'react';
import { CustomerServiceOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
const App: React.FC = () => (
<>
}
/>
}
/>
>
);
export default App;
```
### Content
Setting the `content` property allows you to show a FloatButton with a description.
> supported only when `shape` is `square`. Due to narrow space for text, short sentence is recommended.
```tsx
import React from 'react';
import { FileTextOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
const App: React.FC = () => (
<>
}
content="HELP INFO"
shape="square"
style={{ insetInlineEnd: 24 }}
/>
}
content="HELP"
shape="square"
style={{ insetInlineEnd: 164 }}
/>
>
);
export default App;
```
### FloatButton with tooltip
Setting the `tooltip` property shows the FloatButton with a tooltip.
```tsx
import React from 'react';
import { FloatButton } from 'antd';
const App: React.FC = () => (
<>
Documents } />
>
);
export default App;
```
### FloatButton Group
When multiple buttons are used together, `
` is recommended. By setting the `shape` property of FloatButton.Group, you can change the shape of group. The `shape` of the FloatButton.Group will override the `shape` of FloatButtons inside.
```tsx
import React from 'react';
import { QuestionCircleOutlined, SyncOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
const App: React.FC = () => (
<>
} />
} />
} />
>
);
export default App;
```
### Menu mode
Open menu mode with `trigger`, which could be `hover` or `click`.
```tsx
import React from 'react';
import { CommentOutlined, CustomerServiceOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
const App: React.FC = () => (
<>
}
>
} />
}
>
} />
>
);
export default App;
```
### Controlled mode
Set the component to controlled mode through `open`, which need to be used together with `trigger`.
```tsx
import React, { useState } from 'react';
import { CommentOutlined, CustomerServiceOutlined } from '@ant-design/icons';
import { FloatButton, Switch } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState
(true);
return (
<>
}
>
} />
}
>
} />
>
);
};
export default App;
```
### placement
Customize animation placement, providing four preset placement: `top`, `right`, `bottom`, `left`, the `top` position by default.
```tsx
import React from 'react';
import {
CommentOutlined,
DownOutlined,
LeftOutlined,
RightOutlined,
UpOutlined,
} from '@ant-design/icons';
import { Flex, FloatButton } from 'antd';
const BOX_SIZE = 100;
const BUTTON_SIZE = 40;
const wrapperStyle: React.CSSProperties = {
width: '100%',
height: '100vh',
overflow: 'hidden',
position: 'relative',
};
const boxStyle: React.CSSProperties = {
width: BOX_SIZE,
height: BOX_SIZE,
position: 'relative',
};
const insetInlineEnd: React.CSSProperties['insetInlineEnd'][] = [
(BOX_SIZE - BUTTON_SIZE) / 2,
-(BUTTON_SIZE / 2),
(BOX_SIZE - BUTTON_SIZE) / 2,
BOX_SIZE - BUTTON_SIZE / 2,
];
const bottom: React.CSSProperties['bottom'][] = [
BOX_SIZE - BUTTON_SIZE / 2,
(BOX_SIZE - BUTTON_SIZE) / 2,
-BUTTON_SIZE / 2,
(BOX_SIZE - BUTTON_SIZE) / 2,
];
const icons = [
,
,
,
,
];
const App: React.FC = () => (
{(['top', 'right', 'bottom', 'left'] as const).map((placement, i) => {
const style: React.CSSProperties = {
position: 'absolute',
insetInlineEnd: insetInlineEnd[i],
bottom: bottom[i],
};
return (
} />
);
})}
);
export default App;
```
### BackTop
`BackTop` makes it easy to go back to the top of the page.
```tsx
import React from 'react';
import { FloatButton } from 'antd';
const App: React.FC = () => (
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
);
export default App;
```
### badge
FloatButton with Badge.
```tsx
import React from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
const App: React.FC = () => (
<>
custom badge color }
badge={{ count: 5, color: 'blue' }}
/>
} />
>
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of FloatButton by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
import type { FloatButtonProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
root: {
border: `1px solid ${token.colorBorder}`,
borderRadius: token.borderRadius,
padding: `${token.paddingXS}px ${token.padding}px`,
height: 'auto',
},
content: {
color: token.colorText,
},
}));
const stylesObject: FloatButtonProps['styles'] = {
root: {
boxShadow: '0 1px 2px 0 rgba(0,0,0,0.05)',
},
};
const stylesFn: FloatButtonProps['styles'] = (
info,
): GetProp => {
if (info.props.type === 'primary') {
return {
root: {
backgroundColor: '#171717',
},
content: {
color: '#fff',
},
};
}
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
return (
custom style class}
/>
}
/>
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
> This component is available since `antd@5.0.0`.
### common API
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| icon | Set the icon component of button | ReactNode | - | | FloatButton: ×, BackTop: 5.27.0 |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| content | Text and other | ReactNode | - | | × |
| ~~description~~ | Please use `content` instead | ReactNode | - | | × |
| tooltip | The text shown in the tooltip | ReactNode \| [TooltipProps](/components/tooltip#api) | - | TooltipProps: 5.25.0 | × |
| type | Setting button type | `default` \| `primary` | `default` | | × |
| shape | Setting button shape | `circle` \| `square` | `circle` | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| onClick | Set the handler to handle `click` event | (event) => void | - | | × |
| href | The target of hyperlink | string | - | | × |
| target | Specifies where to display the linked URL | string | - | | × |
| htmlType | Set the original html `type` of `button`, see: [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#type) | `submit` \| `reset` \| `button` | `button` | 5.21.0 | × |
| badge | Attach Badge to FloatButton. `status` and other props related are not supported. | [BadgeProps](/components/badge#api) | - | 5.4.0 | × |
| disabled | Whether the button is disabled | boolean | - | 6.4.0 | × |
### FloatButton.Group
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| open | Whether the menu is visible or not, use it with trigger | boolean | - | | × |
| closeIcon | Customize close button icon | React.ReactNode | ` ` | | 5.16.0 |
| placement | Customize menu animation placement | `top` \| `left` \| `right` \| `bottom` | `top` | 5.21.0 | × |
| shape | Setting button shape of children | `circle` \| `square` | `circle` | | × |
| trigger | Which action can trigger menu open/close | `click` \| `hover` | - | | × |
| onOpenChange | Callback executed when active menu is changed, use it with trigger | (open: boolean) => void | - | | × |
| onClick | Set the handler to handle `click` event (only work in `Menu mode`) | (event) => void | - | 5.3.0 | × |
### FloatButton.BackTop
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| duration | Time to return to top(ms) | number | 450 | |
| target | Specifies the scrollable area dom node | () => HTMLElement | () => window | |
| visibilityHeight | The BackTop button will not show until the scroll height reaches this value | number | 400 | |
| onClick | A callback function, which can be executed when you click the button | () => void | - | |
## Semantic DOM
### FloatButton
https://ant.design/components/float-button/semantic.md
### FloatButton.Group
https://ant.design/components/float-button/semantic_group.md
## Design Token
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadius | Border radius of base components | number | |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| boxShadowSecondary | Control the secondary box shadow style of an element. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| controlHeight | The height of the basic controls such as buttons and input boxes in Ant Design | number | |
| controlHeightLG | LG component height | number | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeIcon | Control the font size of operation icon in Select, Cascader, etc. Normally same as fontSizeSM. | number | |
| fontSizeSM | Small font size | number | |
| lineHeight | Line height of text. | number | |
| marginLG | Control the margin of an element, with a large size. | number | |
| marginXXL | Control the margin of an element, with the largest size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| padding | Control the padding of the element. | number | |
| paddingXXS | Control the extra extra small padding of the element. | number | |
| zIndexPopupBase | Base zIndex of component like FloatButton, Affix which can be cover by large popup | number | |
---
## form
Source: https://ant.design/components/form.md
---
category: Components
group: Data Entry
title: Form
description: High-performance form component with data domain management. Includes data entry, validation, and corresponding styles.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*-lcdS5Qm1bsAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*ylFATY6w-ygAAAAAAAAAAAAADrJ8AQ/original
---
## When to use {#when-to-use}
- When you need to create an instance or collect information.
- When you need to validate fields in certain rules.
## Examples
### Basic Usage
Basic Form data control. Includes layout, initial values, validation and submit.
```tsx
import React from 'react';
import type { FormProps } from 'antd';
import { Button, Checkbox, Form, Input } from 'antd';
type FieldType = {
username?: string;
password?: string;
remember?: string;
};
const onFinish: FormProps['onFinish'] = (values) => {
console.log('Success:', values);
};
const onFinishFailed: FormProps['onFinishFailed'] = (errorInfo) => {
console.log('Failed:', errorInfo);
};
const App: React.FC = () => (
label="Username"
name="username"
rules={[{ required: true, message: 'Please input your username!' }]}
>
label="Password"
name="password"
rules={[{ required: true, message: 'Please input your password!' }]}
>
name="remember" valuePropName="checked" label={null}>
Remember me
Submit
);
export default App;
```
### Form methods
Call form method with `Form.useForm`.
> Note that `useForm` is a [React Hooks](https://react.dev/reference/react/hooks) that only works in functional component. You can also use `ref` to get the form instance in class component: https://codesandbox.io/p/sandbox-ngtjtm
```tsx
import React from 'react';
import { Button, Form, Input, Select, Space } from 'antd';
const layout = {
labelCol: { span: 8 },
wrapperCol: { span: 16 },
};
const tailLayout = {
wrapperCol: { offset: 8, span: 16 },
};
const App: React.FC = () => {
const [form] = Form.useForm();
const onGenderChange = (value: string) => {
switch (value) {
case 'male':
form.setFieldsValue({ note: 'Hi, man!' });
break;
case 'female':
form.setFieldsValue({ note: 'Hi, lady!' });
break;
case 'other':
form.setFieldsValue({ note: 'Hi there!' });
break;
default:
}
};
const onFinish = (values: any) => {
console.log(values);
};
const onReset = () => {
form.resetFields();
};
const onFill = () => {
form.setFieldsValue({ note: 'Hello world!', gender: 'male' });
};
return (
prevValues.gender !== currentValues.gender}
>
{({ getFieldValue }) =>
getFieldValue('gender') === 'other' ? (
) : null
}
Submit
Reset
Fill form
);
};
export default App;
```
### Form Layout
There are three layout for form: `horizontal`, `vertical`, `inline`.
```tsx
import React, { useState } from 'react';
import { Button, Form, Input, Radio } from 'antd';
import type { FormProps } from 'antd';
type LayoutType = Parameters[0]['layout'];
const App: React.FC = () => {
const [form] = Form.useForm();
const [formLayout, setFormLayout] = useState('horizontal');
const onFormLayoutChange: FormProps['onValuesChange'] = ({ layout }) => {
setFormLayout(layout);
};
return (
Horizontal
Vertical
Inline
Submit
);
};
export default App;
```
### Form mix layout
Defining a separate `layout` on `Form.Item` can achieve multiple layouts for a single form.
```tsx
import React from 'react';
import { Divider, Form, Input } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### Form disabled
Set component to disabled, only works for antd components.
```tsx
import React, { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import {
Button,
Cascader,
Checkbox,
ColorPicker,
DatePicker,
Form,
Input,
InputNumber,
Mentions,
Radio,
Rate,
Select,
Slider,
Switch,
Transfer,
Tree,
TreeSelect,
Upload,
} from 'antd';
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const normFile = (e: any) => {
if (Array.isArray(e)) {
return e;
}
return e?.fileList;
};
const FormDisabledDemo: React.FC = () => {
const [componentDisabled, setComponentDisabled] = useState(true);
return (
<>
setComponentDisabled(e.target.checked)}
>
Form disabled
Checkbox
Apple
Pear
Upload
Button
({
key: i.toString(),
title: `Content ${i + 1}`,
description: `Description of content ${i + 1}`,
}))}
targetKeys={['1', '3', '5']}
render={(item) => item.title}
/>
>
);
};
export default () => ;
```
### Form variants
Change the variant of all components in the form, options include: `outlined` `filled` `borderless` and `underlined`.
```tsx
import React from 'react';
import {
Button,
Cascader,
DatePicker,
Form,
Input,
InputNumber,
Mentions,
Segmented,
Select,
TreeSelect,
} from 'antd';
const { RangePicker } = DatePicker;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const App: React.FC = () => {
const [form] = Form.useForm();
const variant = Form.useWatch('variant', form);
return (
Submit
);
};
export default App;
```
### Required style
Switch required or optional style with `requiredMark`.
```tsx
import React, { useState } from 'react';
import { InfoCircleOutlined } from '@ant-design/icons';
import { Button, Form, Input, Radio, Tag } from 'antd';
import type { FormProps } from 'antd';
type RequiredMark = boolean | 'optional' | 'customize';
const customizeRequiredMark = (label: React.ReactNode, { required }: { required: boolean }) => (
<>
{required ? Required : optional }
{label}
>
);
const App: React.FC = () => {
const [form] = Form.useForm();
const [requiredMark, setRequiredMark] = useState('optional');
const onRequiredTypeChange: FormProps['onValuesChange'] = ({ requiredMarkValue }) => {
setRequiredMark(requiredMarkValue);
};
return (
Default
Optional
Hidden
Customize
}}
>
Submit
);
};
export default App;
```
### Form size
Set component size, only works for antd components.
```tsx
import React, { useState } from 'react';
import {
Button,
Cascader,
DatePicker,
Form,
Input,
InputNumber,
Radio,
Select,
Switch,
TreeSelect,
} from 'antd';
import type { FormProps } from 'antd';
type SizeType = Parameters[0]['size'];
const App: React.FC = () => {
const [componentSize, setComponentSize] = useState('medium');
const onFormLayoutChange: FormProps['onValuesChange'] = ({ size }) => {
setComponentSize(size);
};
return (
Small
Medium
Large
Button
);
};
export default App;
```
### label can wrap
Turn on `labelWrap` to wrap label if text is long.
```tsx
import React from 'react';
import { Button, Form, Input } from 'antd';
const App: React.FC = () => (
Submit
);
export default App;
```
### No block rule
`rule` with `warningOnly` will not block form submit.
```tsx
import React from 'react';
import { Button, Form, Input, message, Space } from 'antd';
const App: React.FC = () => {
const [messageApi, contextHolder] = message.useMessage();
const [form] = Form.useForm();
const onFinish = () => {
messageApi.success('Submit success!');
};
const onFinishFailed = () => {
messageApi.error('Submit failed!');
};
const onFill = () => {
form.setFieldsValue({
url: 'https://taobao.com/',
});
};
return (
<>
{contextHolder}
Submit
Fill
>
);
};
export default App;
```
### Watch Hooks
`useWatch` helps watch the field change and only re-render for the value change. [API Ref](#formusewatch).
```tsx
import React from 'react';
import { Form, Input, InputNumber, Typography } from 'antd';
const Demo: React.FC = () => {
const [form] = Form.useForm<{ name: string; age: number }>();
const nameValue = Form.useWatch('name', form);
// The selector is static and does not support closures.
const customValue = Form.useWatch((values) => `name: ${values.name || ''}`, form);
return (
<>
Name Value: {nameValue}
Custom Value: {customValue}
>
);
};
export default Demo;
```
### Validate Trigger
For the async validation scenario, high frequency of verification will cause backend pressure. You can change the verification timing through `validateTrigger`, or change the verification frequency through `validateDebounce`, or set the verification short circuit through `validateFirst`.
```tsx
import React from 'react';
import { Alert, Form, Input } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Validate Only
Dynamic adjust submit button's `disabled` status by `validateOnly` of `validateFields`.
```tsx
import React from 'react';
import type { FormInstance } from 'antd';
import { Button, Form, Input, Space } from 'antd';
interface SubmitButtonProps {
form: FormInstance;
}
const SubmitButton: React.FC> = ({ form, children }) => {
const [submittable, setSubmittable] = React.useState(false);
// Watch all values
const values = Form.useWatch([], form);
React.useEffect(() => {
form
.validateFields({ validateOnly: true })
.then(() => setSubmittable(true))
.catch(() => setSubmittable(false));
}, [form, values]);
return (
{children}
);
};
const App: React.FC = () => {
const [form] = Form.useForm();
return (
Submit
Reset
);
};
export default App;
```
### Path Prefix
In some scenarios, you may want to set a prefix for some fields consistently. You can achieve this effect with HOC.
```tsx
import React from 'react';
import { Button, Form, Input } from 'antd';
import type { FormItemProps } from 'antd';
const MyFormItemContext = React.createContext<(string | number)[]>([]);
interface MyFormItemGroupProps {
prefix: string | number | (string | number)[];
}
function toArr(str: string | number | (string | number)[]): (string | number)[] {
return Array.isArray(str) ? str : [str];
}
const MyFormItemGroup: React.FC> = ({
prefix,
children,
}) => {
const prefixPath = React.useContext(MyFormItemContext);
const concatPath = React.useMemo(() => [...prefixPath, ...toArr(prefix)], [prefixPath, prefix]);
return {children} ;
};
const MyFormItem = ({ name, ...props }: FormItemProps) => {
const prefixPath = React.useContext(MyFormItemContext);
const concatName = name !== undefined ? [...prefixPath, ...toArr(name)] : undefined;
return ;
};
const App: React.FC = () => {
const onFinish = (value: object) => {
console.log(value);
};
return (
);
};
export default App;
```
### Dynamic Form Item
Add or remove form items dynamically. `add` function support config initial value.
```css
.dynamic-delete-button {
position: relative;
top: 4px;
margin: 0 8px;
color: #999;
font-size: 24px;
cursor: pointer;
transition: all 0.3s;
}
.dynamic-delete-button:hover {
color: #777;
}
.dynamic-delete-button[disabled] {
cursor: not-allowed;
opacity: 0.5;
}
```
```tsx
import React from 'react';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Form, Input } from 'antd';
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 4 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 20 },
},
};
const formItemLayoutWithOutLabel = {
wrapperCol: {
xs: { span: 24, offset: 0 },
sm: { span: 20, offset: 4 },
},
};
const App: React.FC = () => {
const onFinish = (values: any) => {
console.log('Received values of form:', values);
};
return (
{
if (!names || names.length < 2) {
return Promise.reject(new Error('At least 2 passengers'));
}
},
},
]}
>
{(fields, { add, remove }, { errors }) => (
<>
{fields.map((field, index) => (
{fields.length > 1 ? (
remove(field.name)}
/>
) : null}
))}
add()}
style={{ width: '60%' }}
icon={ }
>
Add field
{
add('The head item', 0);
}}
style={{ width: '60%', marginTop: '20px' }}
icon={ }
>
Add field at head
>
)}
Submit
);
};
export default App;
```
### Dynamic Form nest Items
Nest dynamic field need extends `field`. Pass `field.name` to nest item.
```tsx
import React from 'react';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Form, Input, Space } from 'antd';
const onFinish = (values: any) => {
console.log('Received values of form:', values);
};
const App: React.FC = () => (
{(fields, { add, remove }) => (
<>
{fields.map(({ key, name, ...restField }) => (
remove(name)} />
))}
add()} block icon={ }>
Add field
>
)}
Submit
);
export default App;
```
### Complex Dynamic Form Item
Multiple Form.List nested usage scenarios.
```tsx
import React from 'react';
import { CloseOutlined } from '@ant-design/icons';
import { Button, Card, Form, Input, Space, Typography } from 'antd';
const App: React.FC = () => {
const [form] = Form.useForm();
return (
{(fields, { add, remove }) => (
)}
{() => (
{JSON.stringify(form.getFieldsValue(), null, 2)}
)}
);
};
export default App;
```
### Nest
`name` prop support nest data structure. Customize validate message template with `validateMessages` or `message`. Ref [here](https://github.com/react-component/field-form/blob/master/src/utils/messages.ts) about message template.
```tsx
import React from 'react';
import { Button, Form, Input, InputNumber } from 'antd';
const layout = {
labelCol: { span: 8 },
wrapperCol: { span: 16 },
};
const validateMessages = {
required: '${label} is required!',
types: {
email: '${label} is not a valid email!',
number: '${label} is not a valid number!',
},
number: {
range: '${label} must be between ${min} and ${max}',
},
};
const onFinish = (values: any) => {
console.log(values);
};
const App: React.FC = () => (
Submit
);
export default App;
```
### complex form control
This demo shows how to use `Form.Item` with multiple controls. ` ` will only bind the control(Input/Select) which is the only children of it. Imagine this case: you added some text description after the Input, then you have to wrap the Input by an extra ``. `style` property of `Form.Item` could be useful to modify the nested form item layout, or use ` ` to turn it into a pure form-binded component(like `getFieldDecorator` in 3.x).
```diff
-
-
-
+
+ // that will bind input
+ description
+
```
This demo shows three typical usages:
- `Username`: extra elements after control, using ` ` inside `Form.Item` to bind Input.
- `Address`: two controls in one line, using two ` ` to bind each control.
- `BirthDate`:two controls in one line with independent error message, using two ` ` to bind each control, make layout inline by customizing `style` property.
> Note that, in this case, no more `name` property should be left in Form.Item with label.
See the `Customized Form Controls` demo below for more advanced usage.
```tsx
import React from 'react';
import { Button, Form, Input, Select, Space, Tooltip, Typography } from 'antd';
const onFinish = (values: any) => {
console.log('Received values of form: ', values);
};
const App: React.FC = () => (
Need Help?
Submit
);
export default App;
```
### Customized Form Controls
Customized or third-party form controls can be used in Form, too. Controls must follow these conventions:
> - It has a controlled property `value` or other name which is equal to the value of [`valuePropName`](#formitem).
> - It has event `onChange` or an event which name is equal to the value of [`trigger`](#formitem).
> - Forward the ref or pass the id property to dom to support the `scrollToField` method.
```tsx
import React, { useState } from 'react';
import { Button, Form, Input, Select } from 'antd';
type Currency = 'rmb' | 'dollar';
interface PriceValue {
number?: number;
currency?: Currency;
}
interface PriceInputProps {
id?: string;
value?: PriceValue;
onChange?: (value: PriceValue) => void;
}
const PriceInput: React.FC = (props) => {
const { id, value = {}, onChange } = props;
const [number, setNumber] = useState(0);
const [currency, setCurrency] = useState('rmb');
const triggerChange = (changedValue: { number?: number; currency?: Currency }) => {
onChange?.({ number, currency, ...value, ...changedValue });
};
const onNumberChange = (e: React.ChangeEvent) => {
const newNumber = Number.parseInt(e.target.value || '0', 10);
if (Number.isNaN(number)) {
return;
}
if (!('number' in value)) {
setNumber(newNumber);
}
triggerChange({ number: newNumber });
};
const onCurrencyChange = (newCurrency: Currency) => {
if (!('currency' in value)) {
setCurrency(newCurrency);
}
triggerChange({ currency: newCurrency });
};
return (
);
};
const App: React.FC = () => {
const onFinish = (values: any) => {
console.log('Received values from form: ', values);
};
const checkPrice = (_: any, value: { number: number }) => {
if (value.number > 0) {
return Promise.resolve();
}
return Promise.reject(new Error('Price must be greater than zero!'));
};
return (
Submit
);
};
export default App;
```
### Store Form Data into Upper Component
We can store form data into upper component or [Redux](https://github.com/reactjs/redux) or [dva](https://github.com/dvajs/dva) by using `onFieldsChange` and `fields`, see more at this [rc-field-form demo](https://rc-field-form.react-component.now.sh/?selectedKind=rc-field-form&selectedStory=StateForm-redux&full=0&addons=1&stories=1&panelRight=0&addonPanel=storybook%2Factions%2Factions-panel).
`onFieldsChange` returns a flat `FieldData[]`. When a field uses an array name path, `FieldData.name` keeps that path instead of converting it into a nested object, making it easier to process each field entry in the external state.
**Note:** Saving form data globally [is not a good practice](https://github.com/reduxjs/redux/issues/1287#issuecomment-175351978). You should avoid this if not necessary.
```tsx
import React, { useState } from 'react';
import { Form, Input, Typography } from 'antd';
const { Paragraph } = Typography;
interface FieldData {
name: string | number | (string | number)[];
value?: unknown;
touched?: boolean;
validating?: boolean;
errors?: string[];
}
interface CustomizedFormProps {
onChange: (fields: FieldData[]) => void;
fields: FieldData[];
}
const CustomizedForm: React.FC = ({ onChange, fields }) => (
);
const App: React.FC = () => {
const [fields, setFields] = useState([
{ name: ['username'], value: 'Ant Design' },
{ name: ['profile', 'email'], value: 'antd@example.com' },
]);
return (
<>
{
setFields(newFields);
}}
/>
{JSON.stringify(fields, null, 2)}
>
);
};
export default App;
```
### Control between forms
Use `Form.Provider` to process data between forms. In this case, submit button is in the Modal which is out of Form. You can use `form.submit` to submit form. Besides, we recommend native ` ` to submit a form.
```tsx
import React, { useEffect, useRef, useState } from 'react';
import { SmileOutlined, UserOutlined } from '@ant-design/icons';
import { Avatar, Button, Flex, Form, Input, InputNumber, Modal, Space, Typography } from 'antd';
import type { GetRef } from 'antd';
type FormInstance = GetRef;
const layout = {
labelCol: { span: 8 },
wrapperCol: { span: 16 },
};
const tailLayout = {
wrapperCol: { offset: 8, span: 16 },
};
interface UserType {
name: string;
age: string;
}
interface ModalFormProps {
open: boolean;
onCancel: () => void;
}
// reset form fields when modal is form, closed
const useResetFormOnCloseModal = ({ form, open }: { form: FormInstance; open: boolean }) => {
const prevOpenRef = useRef(null);
useEffect(() => {
prevOpenRef.current = open;
}, [open]);
const prevOpen = prevOpenRef.current;
useEffect(() => {
if (!open && prevOpen) {
form.resetFields();
}
}, [form, prevOpen, open]);
};
const ModalForm: React.FC = ({ open, onCancel }) => {
const [form] = Form.useForm();
useResetFormOnCloseModal({
form,
open,
});
const onOk = () => {
form.submit();
};
return (
);
};
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showUserModal = () => {
setOpen(true);
};
const hideUserModal = () => {
setOpen(false);
};
const onFinish = (values: any) => {
console.log('Finish:', values);
};
return (
{
if (name === 'userForm') {
const { basicForm } = forms;
const users = basicForm.getFieldValue('users') || [];
basicForm.setFieldsValue({ users: [...users, values] });
setOpen(false);
}
}}
>
{/* Create a hidden field to make Form instance record this */}
prevValues.users !== curValues.users}
>
{({ getFieldValue }) => {
const users: UserType[] = getFieldValue('users') || [];
return users.length ? (
{users.map((user) => (
} />
{`${user.name} - ${user.age}`}
))}
) : (
( No user yet. )
);
}}
Submit
Add User
);
};
export default App;
```
### Inline Login Form
Inline login form is often used in navigation bar.
```tsx
import React, { useEffect, useState } from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input } from 'antd';
const App: React.FC = () => {
const [form] = Form.useForm();
const [clientReady, setClientReady] = useState(false);
// To disable submit button at the beginning.
useEffect(() => {
setClientReady(true);
}, []);
const onFinish = (values: any) => {
console.log('Finish:', values);
};
return (
} placeholder="Username" />
} type="password" placeholder="Password" />
{() => (
errors.length).length
}
>
Log in
)}
);
};
export default App;
```
### Login Form
Normal login form which can contain more elements.
```tsx
import React from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Flex, Form, Input } from 'antd';
const App: React.FC = () => {
const onFinish = (values: any) => {
console.log('Received values of form: ', values);
};
return (
} placeholder="Username" />
} type="password" placeholder="Password" />
Remember me
Forgot password
Log in
or Register now!
);
};
export default App;
```
### Registration
Fill in this form to create a new account for you.
```tsx
import React, { useState } from 'react';
import type { CascaderProps, FormItemProps, FormProps } from 'antd';
import {
AutoComplete,
Button,
Cascader,
Checkbox,
Col,
Form,
Input,
InputNumber,
Row,
Select,
Space,
} from 'antd';
import type { DefaultOptionType } from 'antd/es/select';
interface FormCascaderOption {
value: string;
label: string;
children?: FormCascaderOption[];
}
const residences: CascaderProps['options'] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const formItemLayout: FormProps = {
labelCol: {
xs: { span: 24 },
sm: { span: 8 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
};
const tailFormItemLayout: FormItemProps = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 16,
offset: 8,
},
},
};
interface PhoneValue {
prefix?: string;
phone?: string;
}
interface PhoneInputProps {
id?: string;
value?: PhoneValue;
onChange?: (value: PhoneValue) => void;
}
const PhoneInput: React.FC = ({ id, value = {}, onChange }) => {
const [prefix, setPrefix] = useState('86');
const [phone, setPhone] = useState('');
const triggerChange = (changedValue: PhoneValue) => {
onChange?.({ ...value, ...changedValue });
};
const onPrefixChange = (newPrefix: string) => {
if (!('prefix' in value)) {
setPrefix(newPrefix);
}
triggerChange({ prefix: newPrefix });
};
const onPhoneChange = (e: React.ChangeEvent) => {
const newPhone = e.target.value;
if (!('phone' in value)) {
setPhone(newPhone);
}
triggerChange({ phone: newPhone });
};
return (
);
};
interface DonationValue {
amount?: number;
currency?: string;
}
interface DonationInputProps {
id?: string;
value?: DonationValue;
onChange?: (value: DonationValue) => void;
}
const DonationInput: React.FC = ({ id, value = {}, onChange }) => {
const [amount, setAmount] = useState();
const [currency, setCurrency] = useState('USD');
const triggerChange = (changedValue: DonationValue) => {
onChange?.({ ...value, ...changedValue });
};
const onAmountChange = (newAmount: number | null) => {
if (!('amount' in value)) {
setAmount(newAmount ?? undefined);
}
triggerChange({ amount: newAmount ?? undefined });
};
const onCurrencyChange = (newCurrency: string) => {
if (!('currency' in value)) {
setCurrency(newCurrency);
}
triggerChange({ currency: newCurrency });
};
return (
);
};
const App: React.FC = () => {
const [form] = Form.useForm();
const onFinish = (values: any) => {
console.log('Received values of form: ', values);
};
const [autoCompleteResult, setAutoCompleteResult] = useState([]);
const onWebsiteChange = (value: string) => {
setAutoCompleteResult(
value ? ['.com', '.org', '.net'].map((domain) => `${value}${domain}`) : [],
);
};
const websiteOptions = autoCompleteResult.map((website) => ({
label: website,
value: website,
}));
return (
({
validator(_, value) {
if (!value || getFieldValue('password') === value) {
return Promise.resolve();
}
return Promise.reject(new Error('The new password that you entered do not match!'));
},
}),
]}
>
Get captcha
value ? Promise.resolve() : Promise.reject(new Error('Should accept agreement')),
},
]}
{...tailFormItemLayout}
>
I have read the agreement
Register
);
};
export default App;
```
### Advanced search
Three columns layout is often used for advanced searching of data table.
Because the width of label is not fixed, you may need to adjust it by customizing its style.
```tsx
import React, { useState } from 'react';
import { DownOutlined } from '@ant-design/icons';
import { Button, Col, Form, Input, Row, Select, Space, theme } from 'antd';
const AdvancedSearchForm = () => {
const { token } = theme.useToken();
const [form] = Form.useForm();
const [expand, setExpand] = useState(false);
const formStyle: React.CSSProperties = {
maxWidth: 'none',
background: token.colorFillAlter,
borderRadius: token.borderRadiusLG,
padding: 24,
};
const getFields = () => {
const count = expand ? 10 : 6;
const children: React.ReactNode[] = [];
for (let i = 0; i < count; i++) {
children.push(
{i % 3 !== 1 ? (
) : (
)}
,
);
}
return children;
};
const onFinish = (values: any) => {
console.log('Received values of form: ', values);
};
return (
);
};
const App: React.FC = () => {
const { token } = theme.useToken();
const listStyle: React.CSSProperties = {
lineHeight: '200px',
textAlign: 'center',
background: token.colorFillAlter,
borderRadius: token.borderRadiusLG,
marginTop: 16,
};
return (
<>
Search Result List
>
);
};
export default App;
```
### Form in Modal to Create
When user visit a page with a list of items, and want to create a new item. The page can popup a form in Modal, then let user fill in the form to create an item.
```tsx
import React, { useState } from 'react';
import { Button, Form, Input, Modal, Radio } from 'antd';
interface Values {
title?: string;
description?: string;
modifier?: string;
}
const App: React.FC = () => {
const [form] = Form.useForm();
const [formValues, setFormValues] = useState();
const [open, setOpen] = useState(false);
const onCreate = (values: Values) => {
console.log('Received values of form: ', values);
setFormValues(values);
setOpen(false);
};
return (
<>
setOpen(true)}>
New Collection
{JSON.stringify(formValues, null, 2)}
setOpen(false)}
destroyOnHidden
modalRender={(dom) => (
)}
>
Public
Private
>
);
};
export default App;
```
### Time-related Controls
The `value` of time-related components is a `dayjs` object, which we need to pre-process it before we submit to server.
```tsx
import React from 'react';
import { Button, DatePicker, Form, TimePicker } from 'antd';
const { RangePicker } = DatePicker;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 8 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
};
const config = {
rules: [{ type: 'object' as const, required: true, message: 'Please select time!' }],
};
const rangeConfig = {
rules: [{ type: 'array' as const, required: true, message: 'Please select time!' }],
};
const onFinish = (fieldsValue: any) => {
// Should format date value before submit.
const rangeValue = fieldsValue['range-picker'];
const rangeTimeValue = fieldsValue['range-time-picker'];
const values = {
...fieldsValue,
'date-picker': fieldsValue['date-picker'].format('YYYY-MM-DD'),
'date-time-picker': fieldsValue['date-time-picker'].format('YYYY-MM-DD HH:mm:ss'),
'month-picker': fieldsValue['month-picker'].format('YYYY-MM'),
'range-picker': [rangeValue[0].format('YYYY-MM-DD'), rangeValue[1].format('YYYY-MM-DD')],
'range-time-picker': [
rangeTimeValue[0].format('YYYY-MM-DD HH:mm:ss'),
rangeTimeValue[1].format('YYYY-MM-DD HH:mm:ss'),
],
'time-picker': fieldsValue['time-picker'].format('HH:mm:ss'),
};
console.log('Received values of form: ', values);
};
const App: React.FC = () => (
Submit
);
export default App;
```
### Handle Form Data Manually
`Form` will collect and validate form data automatically. But if you don't need this feature or the default behavior cannot satisfy your business, you can handle form data manually.
```tsx
import React, { useState } from 'react';
import type { InputNumberProps } from 'antd';
import { Form, InputNumber } from 'antd';
type ValidateStatus = Parameters[0]['validateStatus'];
const validatePrimeNumber = (
number: number,
): {
validateStatus: ValidateStatus;
errorMsg: string | null;
} => {
if (number === 11) {
return {
validateStatus: 'success',
errorMsg: null,
};
}
return {
validateStatus: 'error',
errorMsg: 'The prime between 8 and 12 is 11!',
};
};
const formItemLayout = {
labelCol: { span: 7 },
wrapperCol: { span: 12 },
};
const tips =
'A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself.';
const App: React.FC = () => {
const [number, setNumber] = useState<{
value: number;
validateStatus?: ValidateStatus;
errorMsg?: string | null;
}>({ value: 11 });
const onNumberChange: InputNumberProps['onChange'] = (value) => {
setNumber({
...validatePrimeNumber(value as number),
value: value as number,
});
};
return (
);
};
export default App;
```
### Customized Validation
We provide properties like `validateStatus` `help` `hasFeedback` to customize your own validate status and message, without using Form.
1. `validateStatus`: validate status of form components which could be 'success', 'warning', 'error', 'validating'.
2. `hasFeedback`: display feed icon of input control
3. `help`: display validate message.
```tsx
import React from 'react';
import { SmileOutlined } from '@ant-design/icons';
import {
Cascader,
DatePicker,
Form,
Input,
InputNumber,
Mentions,
Select,
TimePicker,
TreeSelect,
} from 'antd';
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const App: React.FC = () => (
} />
-
);
export default App;
```
### Dynamic Rules
Perform different check rules according to different situations.
```tsx
import React, { useEffect, useState } from 'react';
import { Button, Checkbox, Form, Input } from 'antd';
const formItemLayout = {
labelCol: { span: 4 },
wrapperCol: { span: 8 },
};
const formTailLayout = {
labelCol: { span: 4 },
wrapperCol: { span: 8, offset: 4 },
};
const App: React.FC = () => {
const [form] = Form.useForm();
const [checkNick, setCheckNick] = useState(false);
useEffect(() => {
form.validateFields(['nickname']);
}, [checkNick, form]);
const onCheckboxChange = (e: { target: { checked: boolean } }) => {
setCheckNick(e.target.checked);
};
const onCheck = async () => {
try {
const values = await form.validateFields();
console.log('Success:', values);
} catch (errorInfo) {
console.log('Failed:', errorInfo);
}
};
return (
Nickname is required
Check
);
};
export default App;
```
### Dependencies
Form.Item can set the associated field through the `dependencies` property. When the value of the associated field changes, the validation and update will be triggered.
```tsx
import React from 'react';
import { Alert, Form, Input, Typography } from 'antd';
const App: React.FC = () => {
const [form] = Form.useForm();
return (
{/* Field */}
({
validator(_, value) {
if (!value || getFieldValue('password') === value) {
return Promise.resolve();
}
return Promise.reject(new Error('The new password that you entered do not match!'));
},
}),
]}
>
{/* Render Props */}
{() => (
Only Update when password2 updated:
{JSON.stringify(form.getFieldsValue(), null, 2)}
)}
);
};
export default App;
```
### getValueProps + normalize
By combining `getValueProps` and `normalize`, it is possible to convert the format of `value`, such as converting the timestamp into a `dayjs` object and then passing it to the `DatePicker`.
```tsx
import React from 'react';
import type { FormProps } from 'antd';
import { Button, DatePicker, Form } from 'antd';
import dayjs from 'dayjs';
const dateTimestamp = dayjs('2024-01-01').valueOf();
type FieldType = {
date?: string;
};
const onFinish: FormProps['onFinish'] = (values) => {
console.log('Success:', values);
};
const App: React.FC = () => (
label="Date"
name="date"
rules={[{ required: true }]}
getValueProps={(value) => ({ value: value && dayjs(Number(value)) })}
normalize={(value) => value && `${dayjs(value).valueOf()}`}
>
Submit
);
export default App;
```
### Slide to error field
When validation fails or manually scroll to the error field.
```tsx
import React from 'react';
import { Button, Flex, Form, Input, Select } from 'antd';
const App = () => {
const [form] = Form.useForm();
return (
form.scrollToField('bio')}>Scroll to Bio
Submit
form.resetFields()}>
Reset
);
};
export default App;
```
### Other Form Controls
Demonstration of validation configuration for form controls which are not shown in the demos above.
```tsx
import React from 'react';
import { InboxOutlined, UploadOutlined } from '@ant-design/icons';
import {
Button,
Checkbox,
Col,
ColorPicker,
Form,
InputNumber,
Radio,
Rate,
Row,
Select,
Slider,
Space,
Switch,
Upload,
} from 'antd';
const formItemLayout = {
labelCol: { span: 6 },
wrapperCol: { span: 14 },
};
const normFile = (e: any) => {
console.log('Upload event:', e);
if (Array.isArray(e)) {
return e;
}
return e?.fileList;
};
const onFinish = (values: any) => {
console.log('Received values of form: ', values);
};
const App: React.FC = () => (
China
machines
item 1
item 2
item 3
item 1
item 2
item 3
A
B
C
D
E
F
}>Click to upload
Click or drag file to this area to upload
Support for a single or bulk upload.
Submit
reset
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Form by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Button, Form, Input, Space } from 'antd';
import type { FormProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
root: {
padding: token.padding,
maxWidth: 800,
marginTop: 32,
backgroundColor: token.colorBgContainer,
borderRadius: token.borderRadius,
boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
},
}));
const stylesObject: FormProps['styles'] = {
label: {
textAlign: 'end',
color: '#333',
fontWeight: 500,
},
content: {
paddingInlineStart: 12,
},
};
const stylesFunction: FormProps['styles'] = (info): GetProp => {
if (info.props.variant === 'filled') {
return {
root: {
border: '1px solid #1677FF',
},
label: {
textAlign: 'end',
color: '#1677FF',
},
content: {
paddingInlineStart: 12,
},
};
}
return {};
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
const sharedProps: FormProps = {
labelCol: { span: 4 },
wrapperCol: { span: 20 },
autoComplete: 'off',
classNames,
};
const sharedFormContent = (
<>
Submit
reset
>
);
return (
<>
>
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Form
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| colon | Configure the default value of `colon` for Form.Item. Indicates whether the colon after the label is displayed (only effective when prop layout is horizontal) | boolean | true | | 4.18.0 |
| disabled | Set form component disable, only available for antd components | boolean | false | 4.21.0 | × |
| component | Set the Form rendering element. Do not create a DOM node for `false` | ComponentType \| false | form | | × |
| fields | Control of form fields through state management (such as redux). Not recommended for non-strong demand. View [example](#form-demo-global-state) | [FieldData](#fielddata)\[] | - | | × |
| form | Form control instance created by `Form.useForm()`. Automatically created when not provided | [FormInstance](#forminstance) | - | | × |
| feedbackIcons | Can be passed custom icons while `Form.Item` element has `hasFeedback` | [FeedbackIcons](#feedbackicons) | - | 5.9.0 | × |
| initialValues | Set value by Form initialization or reset | object | - | | × |
| labelAlign | The text align of label of all items | `left` \| `right` | `right` | | 6.4.0 |
| labelWrap | whether label can be wrap | boolean | false | 4.18.0 | × |
| labelCol | Label layout, like ` ` component. Set `span` `offset` value like `{span: 3, offset: 12}` or `sm: {span: 3, offset: 12}` | [object](/components/grid/#col) | - | | × |
| layout | Form layout | `horizontal` \| `vertical` \| `inline` | `horizontal` | | × |
| name | Form name. Will be the prefix of Field `id` | string | - | | × |
| preserve | Keep field value even when field removed. You can get the preserve field value by `getFieldsValue(true)` | boolean | true | 4.4.0 | × |
| requiredMark | Required mark style. Can use required mark or optional mark. You can not config to single Form.Item since this is a Form level config | boolean \| `optional` \| ((label: ReactNode, info: { required: boolean }) => ReactNode) | true | `renderProps`: 5.9.0 | 4.8.0 |
| scrollToFirstError | Auto scroll to first failed field when submit | boolean \| [Options](https://github.com/stipsan/scroll-into-view-if-needed/tree/ece40bd9143f48caf4b99503425ecb16b0ad8249#options) \| { focus: boolean } | false | focus: 5.24.0 | 5.2.0 |
| size | Set field component size (antd components only) | `small` \| `medium` \| `large` | - | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| tooltip | Config tooltip props | [TooltipProps](/components/tooltip#api) & { icon?: ReactNode } | - | 6.3.0 | 6.3.0 |
| validateMessages | Validation prompt template, description [see below](#validatemessages) | [ValidateMessages](https://github.com/ant-design/ant-design/blob/6234509d18bac1ac60fbb3f92a5b2c6a6361295a/components/locale/en_US.ts#L88-L134) | - | | 4.0.0 |
| validateTrigger | Config field validate trigger | string \| string\[] | `onChange` | 4.3.0 | × |
| variant | Variant of components inside form | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 \| `underlined`: 5.24.0 | 5.19.0 |
| wrapperCol | The layout for input controls, same as `labelCol` | [object](/components/grid/#col) | - | | × |
| onFieldsChange | Trigger when field updated | function(changedFields, allFields) | - | | × |
| onFinish | Trigger after submitting the form and verifying data successfully | function(values) | - | | × |
| onFinishFailed | Trigger after submitting the form and verifying data failed | function({ values, errorFields, outOfDate }) | - | | × |
| onValuesChange | Trigger when value updated | function(changedValues, allValues) | - | | × |
| clearOnDestroy | Clear form values when the form is unmounted | boolean | false | 5.18.0 | × |
> It accepts all props which native forms support but `onSubmit`.
### validateMessages
Form provides [default verification error messages](https://github.com/ant-design/ant-design/blob/6234509d18bac1ac60fbb3f92a5b2c6a6361295a/components/locale/en_US.ts#L88-L134). You can modify the template by configuring `validateMessages` property. A common usage is to configure localization:
```jsx
const validateMessages = {
required: "'${name}' is required!",
// ...
};
;
```
Besides, [ConfigProvider](/components/config-provider/) also provides a global configuration scheme that allows for uniform configuration error notification templates:
```jsx
const validateMessages = {
required: "'${name}' is Required!",
// ...
};
;
```
## Form.Item
Form field component for data bidirectional binding, validation, layout, and so on.
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| colon | Used with `label`, whether to display `:` after label text. | boolean | true | |
| dependencies | Set the dependency field. See [below](#dependencies) | [NamePath](#namepath)\[] | - | |
| extra | The extra prompt message. It is similar to help. Usage example: to display error message and prompt message at the same time | ReactNode | - | |
| getValueFromEvent | Specify how to get value from event or other onChange arguments | (..args: any\[]) => any | - | |
| getValueProps | Additional props with sub component (It's not recommended to generate dynamic function prop by `getValueProps`. Please pass it to child component directly) | (value: any) => Record | - | 4.2.0 |
| hasFeedback | Used with `validateStatus`, this option specifies the validation status icon. Recommended to be used only with `Input`. Also, It can get feedback icons via icons prop. | boolean \| { icons: [FeedbackIcons](#feedbackicons) } | false | icons: 5.9.0 |
| help | The prompt message. If not provided, the prompt message will be generated by the validation rule. | ReactNode | - | |
| hidden | Whether to hide Form.Item (still collect and validate value) | boolean | false | 4.4.0 |
| htmlFor | Set sub label `htmlFor` | string | - | |
| initialValue | Config sub default value. Form `initialValues` get higher priority when conflict | string | - | 4.2.0 |
| label | Label text. When there is no need for a label but it needs to be aligned with a colon, it can be set to null | ReactNode | - | null: 5.22.0 |
| labelAlign | The text alignment of the label | `left` \| `right` | `right` | |
| labelCol | The layout of label. You can set `span` `offset` to something like `{span: 3, offset: 12}` or `sm: {span: 3, offset: 12}` same as with ` `. You can set `labelCol` on Form which will not affect nest Item. If both exists, use Item first | [object](/components/grid/#col) | - | |
| messageVariables | The default validate field info, description [see below](#messagevariables) | Record<string, string> | - | 4.7.0 |
| name | Field name, support array | [NamePath](#namepath) | - | |
| normalize | Normalize value from component value before passing to Form instance. Do not support async | (value, prevValue, prevValues) => any | - | |
| noStyle | No style for `true`, used as a pure field control. Will inherit parent Form.Item `validateStatus` if self `validateStatus` not configured | boolean | false | |
| preserve | Keep field value even when field removed | boolean | true | 4.4.0 |
| required | Display required style. It will be generated by the validation rule | boolean | false | |
| rules | Rules for field validation. Click [here](#form-demo-basic) to see an example | [Rule](#rule)\[] | - | |
| shouldUpdate | Custom field update logic. See [below](#shouldupdate) | boolean \| (prevValue, curValue) => boolean | false | |
| tooltip | Config tooltip content | ReactNode \| ([TooltipProps](/components/tooltip#api) & { icon?: ReactNode }) | - | 4.7.0 |
| trigger | When to collect the value of children node. Click [here](#form-demo-customized-form-controls) to see an example | string | `onChange` | |
| validateDebounce | Delay milliseconds to start validation | number | - | 5.9.0 |
| validateFirst | Whether stop validate on first rule of error for this field. Will parallel validate when `parallel` configured | boolean \| `parallel` | false | `parallel`: 4.5.0 |
| validateStatus | The validation status. If not provided, it will be generated by validation rule. options: `success` `warning` `error` `validating` | string | - | |
| validateTrigger | When to validate the value of children node | string \| string\[] | `onChange` | |
| valuePropName | Props of children node, for example, the prop of Switch or Checkbox is `checked`. This prop is an encapsulation of `getValueProps`, which will be invalid after customizing `getValueProps` | string | `value` | |
| wrapperCol | The layout for input controls, same as `labelCol`. You can set `wrapperCol` on Form which will not affect nest Item. If both exists, use Item first | [object](/components/grid/#col) | - | |
| layout | Form item layout | `horizontal` \| `vertical` | - | 5.18.0 |
After wrapped by `Form.Item` with `name` property, `value`(or other property defined by `valuePropName`) `onChange`(or other property defined by `trigger`) props will be added to form controls, the flow of form data will be handled by Form which will cause:
1. You shouldn't use `onChange` on each form control to **collect data**(use `onValuesChange` of Form), but you can still listen to `onChange`.
2. You cannot set value for each form control via `value` or `defaultValue` prop, you should set default value with `initialValues` of Form. Note that `initialValues` cannot be updated by `setState` dynamically, you should use `setFieldsValue` in that situation.
3. You shouldn't call `setState` manually, please use `form.setFieldsValue` to change value programmatically.
### dependencies
Used when there are dependencies between fields. If a field has the `dependencies` prop, this field will automatically trigger updates and validations when upstream is updated. A common scenario is a user registration form with "password" and "confirm password" fields. The "Confirm Password" validation depends on the "Password" field. After setting `dependencies`, the "Password" field update will re-trigger the validation of "Check Password". You can refer [examples](#form-demo-dependencies).
`dependencies` shouldn't be used together with `shouldUpdate`, since it may result in conflicting update logic.
### FeedbackIcons
`({ status: ValidateStatus, errors: ReactNode, warnings: ReactNode }) => Record`
### shouldUpdate
Form updates only the modified field-related components for performance optimization purposes by incremental update. In most cases, you only need to write code or do validation with the [`dependencies`](#dependencies) property. In some specific cases, such as when a new field option appears with a field value changed, or you just want to keep some area updating by form update, you can modify the update logic of Form.Item via the `shouldUpdate`.
When `shouldUpdate` is `true`, any Form update will cause the Form.Item to be re-rendered. This is very helpful for custom rendering some areas. It should be noted that the child component should be returned in a function, otherwise `shouldUpdate` won't behave correctly:
related issue: [#34500](https://github.com/ant-design/ant-design/issues/34500)
```jsx
{() => {
return {JSON.stringify(form.getFieldsValue(), null, 2)} ;
}}
```
You can ref [example](#form-demo-inline-login) to see detail.
When `shouldUpdate` is a function, it will be called by form values update. Providing original values and current value to compare. This is very helpful for rendering additional fields based on values:
```jsx
prevValues.additional !== curValues.additional}>
{() => {
return (
);
}}
```
You can ref [example](#form-demo-control-hooks) to see detail.
### messageVariables
You can modify the default verification information of Form.Item through `messageVariables`.
```jsx
user}
rules={[{ required: true, message: '${label} is required' }]}
>
```
Since `5.20.2`, when you don't want to convert `${}`, you can use `\\${}` to skip:
```jsx
{ required: true, message: '${label} is convert, \\${label} is not convert' }
// good is convert, ${label} is not convert
```
## Form.List
Provides array management for fields.
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| children | Render function | (fields: Field\[], operation: { add, remove, move }, meta: { errors }) => React.ReactNode | - | |
| initialValue | Config sub default value. Form `initialValues` get higher priority when conflict | any\[] | - | 4.9.0 |
| name | Field name, support array. List is also a field, so it will return all the values by `getFieldsValue`. You can change this logic by [config](#getfieldsvalue) | [NamePath](#namepath) | - | |
| rules | Validate rules, only support customize validator. Should work with [ErrorList](#formerrorlist) | { validator, message }\[] | - | 4.7.0 |
```tsx
{(fields) => (
{fields.map((field) => (
))}
)}
```
Note: You should not configure Form.Item `initialValue` under Form.List. It always should be configured by Form.List `initialValue` or Form `initialValues`.
## operation
Some operator functions in render form of Form.List.
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| add | add form item | (defaultValue?: any, insertIndex?: number) => void | insertIndex | 4.6.0 |
| move | move form item | (from: number, to: number) => void | - | |
| remove | remove form item | (index: number \| number\[]) => void | number\[] | 4.5.0 |
## Form.ErrorList
New in 4.7.0. Show error messages, should only work with `rules` of Form.List. See [example](#form-demo-dynamic-form-item).
| Property | Description | Type | Default |
| -------- | ----------- | ------------ | ------- |
| errors | Error list | ReactNode\[] | - |
## Form.Provider
Provide linkage between forms. If a sub form with `name` prop update, it will auto trigger Provider related events. See [example](#form-demo-form-context).
| Property | Description | Type | Default |
| --- | --- | --- | --- |
| onFormChange | Triggered when a sub form field updates | function(formName: string, info: { changedFields, forms }) | - |
| onFormFinish | Triggered when a sub form submits | function(formName: string, info: { values, forms }) | - |
```jsx
{
if (name === 'form1') {
// Do something...
}
}}
>
```
### FormInstance
| Name | Description | Type | Version |
| --- | --- | --- | --- |
| getFieldError | Get the error messages by the field name | (name: [NamePath](#namepath)) => string\[] | |
| getFieldInstance | Get field instance | (name: [NamePath](#namepath)) => any | 4.4.0 |
| getFieldsError | Get the error messages by the fields name. Return as an array | (nameList?: [NamePath](#namepath)\[]) => FieldError\[] | |
| getFieldsValue | Get values by a set of field names. Return according to the corresponding structure. Default return mounted field value, but you can use `getFieldsValue(true)` to get all values | [GetFieldsValue](#getfieldsvalue) | |
| getFieldValue | Get the value by the field name | (name: [NamePath](#namepath)) => any | |
| isFieldsTouched | Check if fields have been operated. Check if all fields is touched when `allTouched` is `true` | (nameList?: [NamePath](#namepath)\[], allTouched?: boolean) => boolean | |
| isFieldTouched | Check if a field has been operated | (name: [NamePath](#namepath)) => boolean | |
| isFieldValidating | Check field if is in validating | (name: [NamePath](#namepath)) => boolean | |
| resetFields | Reset fields to `initialValues` | (fields?: [NamePath](#namepath)\[]) => void | |
| scrollToField | Scroll to field position | (name: [NamePath](#namepath), options: [ScrollOptions](https://github.com/stipsan/scroll-into-view-if-needed/tree/ece40bd9143f48caf4b99503425ecb16b0ad8249#options) \| { focus: boolean }) => void | focus: 5.24.0 |
| setFields | Set fields status | (fields: [FieldData](#fielddata)\[]) => void | |
| setFieldValue | Set fields value(Will directly pass to form store and **reset validation message**. If you do not want to modify passed object, please clone first) | (name: [NamePath](#namepath), value: any) => void | 4.22.0 |
| setFieldsValue | Set fields value(Will directly pass to form store and **reset validation message**. If you do not want to modify passed object, please clone first). Use `setFieldValue` instead if you want to only config single value in Form.List | (values) => void | |
| submit | Submit the form. It's same as click `submit` button | () => void | |
| validateFields | Validate fields. Use `recursive` to validate all the field in the path | (nameList?: [NamePath](#namepath)\[], config?: [ValidateConfig](#validatefields)) => Promise | |
#### validateFields
```tsx
export interface ValidateConfig {
// New in 5.5.0. Only validate content and not show error message on UI.
validateOnly?: boolean;
// New in 5.9.0. Recursively validate the provided `nameList` and its sub-paths.
recursive?: boolean;
// New in 5.11.0. Validate dirty fields (touched + validated).
// It's useful to validate fields only when they are touched or validated.
dirty?: boolean;
}
```
return sample:
```jsx
validateFields()
.then((values) => {
/*
values:
{
username: 'username',
password: 'password',
}
*/
})
.catch((errorInfo) => {
/*
errorInfo:
{
values: {
username: 'username',
password: 'password',
},
errorFields: [
{ name: ['password'], errors: ['Please input your Password!'] },
],
outOfDate: false,
}
*/
});
```
## Hooks
### Form.useForm
`type Form.useForm = (): [FormInstance]`
Create Form instance to maintain data store.
### Form.useFormInstance
`type Form.useFormInstance = (): FormInstance`
Added in `4.20.0`. Get current context form instance to avoid pass as props between components:
```tsx
const Sub = () => {
const form = Form.useFormInstance();
return form.setFieldsValue({})} />;
};
export default () => {
const [form] = Form.useForm();
return (
);
};
```
### Form.useWatch
`type Form.useWatch = (namePath: NamePath | (selector: (values: Store) => any), formInstance?: FormInstance | WatchOptions): Value`
`5.12.0` add `selector`
Watch the value of a field. You can use this to interact with other hooks like `useSWR` to reduce development costs:
```tsx
const Demo = () => {
const [form] = Form.useForm();
const userName = Form.useWatch('username', form);
const { data: options } = useSWR(`/api/user/${userName}`, fetcher);
return (
);
};
```
If your component is wrapped by `Form.Item`, you can omit the second argument, `Form.useWatch` will find the nearest `FormInstance` automatically.
By default `useWatch` only watches the registered field. If you want to watch the unregistered field, please use `preserve`:
```tsx
const Demo = () => {
const [form] = Form.useForm();
const age = Form.useWatch('age', { form, preserve: true });
console.log(age);
return (
form.setFieldValue('age', 2)}>Update
);
};
```
### Form.Item.useStatus
`type Form.Item.useStatus = (): { status: ValidateStatus | undefined, errors: ReactNode[], warnings: ReactNode[] }`
The `Form.Item.useStatus` hook returns the validation status of a Form.Item and was added in `4.22.0`. When used outside Form.Item, it returns `undefined` for the `status` field. The `errors` and `warnings` fields were added in `5.4.0` to obtain error and warning messages of Form.Item:
```tsx
const CustomInput = ({ value, onChange }) => {
const { status, errors } = Form.Item.useStatus();
return (
);
};
export default () => (
);
```
#### Difference from other data fetching methods
Form only update the Field which changed to avoid full refresh perf issue. Thus you can not get real time value with `getFieldsValue` in render. And `useWatch` will rerender current component to sync with latest value. You can also use Field renderProps to get better performance if only want to do conditional render. If component no need care field value change, you can use `onValuesChange` to give to parent component to avoid current one rerender.
## Interface
### NamePath
`string | number | (string | number)[]`
### GetFieldsValue
`getFieldsValue` provides overloaded methods:
#### getFieldsValue(nameList?: true | [NamePath](#namepath)\[], filterFunc?: FilterFunc)
When `nameList` is empty, return all registered fields, including values of List (even if List has no Item children).
When `nameList` is `true`, return all values in store, including unregistered fields. For example, if you set the value of an unregistered Item through `setFieldsValue`, you can also get all values through `true`.
When `nameList` is an array, return the value of the specified path. Note that `nameList` is a nested array. For example, you need the value of a certain path as follows:
```tsx
// Single path
form.getFieldsValue([['user', 'age']]);
// multiple path
form.getFieldsValue([
['user', 'age'],
['preset', 'account'],
]);
```
#### getFieldsValue({ filter?: FilterFunc })
### FilterFunc
To filter certain field values, `meta` will provide information related to the fields. For example, it can be used to retrieve values that have only been modified by the user, and so on.
```tsx
type FilterFunc = (meta: { touched: boolean; validating: boolean }) => boolean;
```
### FieldData
| Property | Description | Type |
| ---------- | ------------------------ | ------------------------ |
| errors | Error messages | string\[] |
| warnings | Warning messages | string\[] |
| name | Field name path | [NamePath](#namepath)\[] |
| touched | Whether is operated | boolean |
| validating | Whether is in validating | boolean |
| value | Field value | any |
### Rule
Rule supports a config object, or a function returning config object:
```tsx
type Rule = RuleConfig | ((form: FormInstance) => RuleConfig);
```
| Property | Description | Type | Version |
| --- | --- | --- | --- |
| defaultField | Validate rule for all array elements, valid when `type` is `array` | [rule](#rule) | |
| enum | Match enum value. You need to set `type` to `enum` to enable this | any\[] | |
| fields | Validate rule for child elements, valid when `type` is `array` or `object` | Record<string, [rule](#rule)> | |
| len | Length of string, number, array | number | |
| max | `type` required: max length of `string`, `number`, `array` | number | |
| message | Error message. Will auto generate by [template](#validatemessages) if not provided | string \| ReactElement | |
| min | `type` required: min length of `string`, `number`, `array` | number | |
| pattern | Regex pattern | RegExp | |
| required | Required field | boolean | |
| transform | Transform value to the rule before validation | (value) => any | |
| type | Normally `string` \|`number` \|`boolean` \|`url` \| `email` \| `tel`. More type to ref [here](https://github.com/react-component/async-validator#type) | string | |
| validateTrigger | Set validate trigger event. Must be the sub set of `validateTrigger` in Form.Item | string \| string\[] | |
| validator | Customize validation rule. Accept Promise as return. See [example](#form-demo-register) | ([rule](#rule), value) => Promise | |
| warningOnly | Warning only. Not block form submit | boolean | 4.17.0 |
| whitespace | Failed if only has whitespace, only work with `type: 'string'` rule | boolean | |
### WatchOptions
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| form | Form instance | FormInstance | Current form in context | 5.4.0 |
| preserve | Whether to watch the field which has no matched `Form.Item` | boolean | false | 5.4.0 |
## Semantic DOM
https://ant.design/components/form/semantic.md
## Design Token
## Component Token (Form)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| inlineItemMarginBottom | Inline layout form item margin bottom | number | 0 |
| itemMarginBottom | Form item margin bottom | number | 24 |
| labelColonMarginInlineEnd | Label colon margin-inline-end | number | 8 |
| labelColonMarginInlineStart | Label colon margin-inline-start | number | 2 |
| labelColor | Label color | string | rgba(0,0,0,0.88) |
| labelFontSize | Label font size | number | 14 |
| labelHeight | Label height | string \| number | 32 |
| labelRequiredMarkColor | Required mark color | string | #ff4d4f |
| verticalLabelMargin | Vertical layout label margin | Margin \| undefined | 0 |
| verticalLabelPadding | Vertical layout label padding | Padding \| undefined | 0 0 8px |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorBorder | Default border color, used to separate different elements, such as: form separator, card separator, etc. | string | |
| colorError | Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorSuccess | Used to represent the token sequence of operation success, such as Result, Progress and other components will use these map tokens. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDescription | Control the font color of text description. | string | |
| colorWarning | Used to represent the warning map token, such as Notification, Alert, etc. Alert or Control component(like Input) will use these map tokens. | string | |
| controlHeight | The height of the basic controls such as buttons and input boxes in Ant Design | number | |
| controlHeightLG | LG component height | number | |
| controlHeightSM | SM component height | number | |
| controlOutline | Control the outline color of input component. | string | |
| controlOutlineWidth | Control the outline width of input component. | number | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeLG | Large font size | number | |
| lineHeight | Line height of text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| margin | Control the margin of an element, with a medium size. | number | |
| marginLG | Control the margin of an element, with a large size. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
| motionDurationFast | Motion speed, fast speed. Used for small element animation interaction. | string | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionEaseInOut | Preset motion curve. | string | |
| motionEaseOut | Preset motion curve. | string | |
| motionEaseOutBack | Preset motion curve. | string | |
| paddingSM | Control the small padding of the element. | number | |
| screenLGMax | Control the maximum width of large screens. | number | |
| screenMDMax | Control the maximum width of medium screens. | number | |
| screenSMMax | Control the maximum width of small screens. | number | |
| screenXSMax | Control the maximum width of extra small screens. | number | |
## FAQ
### Why can't Segmented be disabled by Form `disabled`? {#faq-segmented-cannot-disabled}
Segmented is designed as a data display component, not a form control component. Although it can be used as a form control similar to Radio, it was not designed for this purpose. Therefore, its behavior is more similar to the Tabs component and will not be disabled by Form's `disabled` prop. For related discussions, see [#54749](https://github.com/ant-design/ant-design/pull/54749#issuecomment-3797737096).
### Why can't Switch, Checkbox bind data? {#faq-switch-checkbox-binding}
Form.Item default bind value to `value` prop, but Switch or Checkbox value prop is `checked`. You can use `valuePropName` to change bind value prop.
```tsx | pure
```
### How does `name` fill value when it's an array? {#faq-name-array-rule}
`name` will fill value by array order. When there exists number in it and no related field in form store, it will auto convert field to array. If you want to keep it as object, use string like: `['1', 'name']`.
### Why is there a form warning when used in Modal? {#faq-form-modal-error}
> Warning: Instance created by `useForm` is not connect to any Form element. Forget to pass `form` prop?
Before Modal opens, children elements do not exist in the view. You can set `forceRender` on Modal to pre-render its children. Click [here](https://codesandbox.io/s/antd-reproduction-template-ibu5c) to view an example.
### Why is component `defaultValue` not working when inside Form.Item? {#faq-item-default-value}
Components inside Form.Item with name property will turn into controlled mode, which makes `defaultValue` not work anymore. Please try `initialValues` of Form to set default value.
### Why can not call `ref` of Form at first time? {#faq-ref-first-call}
`ref` only receives the mounted instance. please ref React official doc:
### Why will `resetFields` re-mount component? {#faq-reset-fields-mount}
`resetFields` will re-mount component under Field to clean up customize component side effects (like async data, cached state, etc.). It's by design.
### Difference between Form initialValues and Item initialValue? {#faq-initial-values-diff}
In most case, we always recommend to use Form `initialValues`. Use Item `initialValue` only with dynamic field usage. Priority follows the rules:
1. Form `initialValues` is the first priority
2. Field `initialValue` is secondary \*. Does not work when multiple Item with same `name` setting the `initialValue`
### Why can't `getFieldsValue` get value at first render? {#faq-get-fields-value}
`getFieldsValue` returns collected field data by default, but the Form.Item node is not ready at the first render. You can get all field data by `getFieldsValue(true)`.
### Why do some components not respond to `setFieldsValue` with `undefined`? {#faq-set-fields-undefined}
`value` change from certain one to `undefined` in React means from controlled mode to uncontrolled mode. Thus it will not change display value but modified FormStore in fact. You can HOC to handle this:
```jsx
const MyInput = ({
// Force use controlled mode
value = '',
...rest
}) => ;
;
```
### Why does `onFieldsChange` trigger three times on change when field sets `rules`? {#faq-rules-trigger-three-times}
Validating is also part of the value updating. It passes through the following steps:
1. Trigger value change
2. Rule validating
3. Rule validated
In each `onFieldsChange`, you will get `false` > `true` > `false` with `isFieldValidating`.
### Why doesn't Form.List support `label` and need ErrorList to show errors? {#faq-form-list-no-label}
Form.List use renderProps which mean internal structure is flexible. Thus `label` and `error` can not have best place. If you want to use antd `label`, you can wrap with Form.Item instead.
### Why can't Form.Item `dependencies` work on Form.List field? {#faq-dependencies-form-list}
Your name path should also contain Form.List `name`:
```tsx
{(fields) =>
fields.map((field) => (
))
}
```
dependencies should be `['users', 0, 'name']`
### Why doesn't `normalize` support async? {#faq-normalize-async}
React cannot get correct interaction of controlled components with async value updates. When a user triggers `onChange`, the component will not respond since the `value` update is async. If you want to trigger value updates asynchronously, you should use a custom component to handle the value state internally and pass synchronous value control to the Form instead.
### `scrollToFirstError` and `scrollToField` not working? {#faq-scroll-not-working}
1. use custom form control
See similar issues: [#28370](https://github.com/ant-design/ant-design/issues/28370) [#27994](https://github.com/ant-design/ant-design/issues/27994)
Starting from version `5.17.0`, the sliding operation will prioritize using the ref element forwarded by the form control elements. Therefore, when considering custom components to support verification scrolling, please consider forwarding it to the form control elements first.
`scrollToFirstError` and `scrollToField` depend on the `id` attribute passed to form controls. Make sure that it hasn't been ignored in your custom form control. Check [codesandbox](https://codesandbox.io/s/antd-reproduction-template-forked-25nul?file=/index.js) for a solution.
2. multiple forms on same page
If there are multiple forms on the page, and there are duplicate same `name` form item, the form scroll probably may find the form item with the same name in another form. You need to set a different `name` for the `Form` component to distinguish it.
### Continue, why not use `ref` to bind element? {#faq-ref-binding}
Form can not get real DOM node when customize component not support `ref`. It will get warning in React Strict Mode if wrap with Class Component and call `findDOMNode`. So we use `id` to locate element.
### `setFieldsValue` do not trigger `onFieldsChange` or `onValuesChange`? {#faq-set-fields-no-trigger}
It's by design. Only user interaction can trigger the change event. This design aims to avoid calling `setFieldsValue` in change events, which may cause infinite loops.
### Why can't `dependencies` respond to `setFieldsValue` updates? {#faq-dependencies-set-fields}
`dependencies` is mainly used for validation linkage between fields. When an upstream field is updated by user interaction, the dependent field will be updated and validated again. If you need to render additional content or switch field options based on values updated by `setFieldsValue`, use `shouldUpdate` or `useWatch` instead.
### Why Form.Item not update value when children is nest? {#faq-item-nested-update}
Form.Item will inject `value` and `onChange` to children when render. Once your field component is wrapped, props will not pass to the correct node. Follow code will not work as expect:
```jsx
I am a wrapped Input
```
You can use HOC to solve this problem, don't forget passing props to form control component:
```jsx
const MyInput = (props) => (
I am a wrapped Input
);
;
```
### Why does clicking the label in the form change the component state? {#faq-label-click-change}
> Related issue: [#47031](https://github.com/ant-design/ant-design/issues/47031), [#43175](https://github.com/ant-design/ant-design/issues/43175), [#52152](https://github.com/ant-design/ant-design/issues/52152)
Form label use [HTML label](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) elements to wrap form controls, which focuses the corresponding control when clicked. This is the native behavior of label elements, designed to improve accessibility and user experience. This standard interaction pattern makes it easier for users to interact with form controls. If you need to disable this behavior, you can use `htmlFor={null}`, though it's generally not recommended.
```diff
-
+
```
### Is there more reference documentation? {#faq-more-docs}
- You can read [《antd v4 Form Best Practices》](https://zhuanlan.zhihu.com/p/375753910) for some usage tips and suggestions (Chinese).
- Want to use before and after in DatePicker and Switch? You can refer to [《How to elegantly add before and after to Form.Item children》](https://zhuanlan.zhihu.com/p/422752055) (Chinese).
- Elegant Form + Modal combination solution [《How to elegantly use Form + Modal》](https://zhuanlan.zhihu.com/p/388222294) (Chinese).
---
## grid
Source: https://ant.design/components/grid.md
---
category: Components
group: Layout
title: Grid
description: 24 Grids System.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*mfJeS6cqZrEAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*DLUwQ4B2_zQAAAAAAAAAAAAADrJ8AQ/original
---
## Design concept
In most business situations, Ant Design needs to solve a lot of information storage problems within the design area, so based on 12 Grids System, we divided the design area into 24 sections.
We name the divided area 'box'. We suggest four boxes for horizontal arrangement at most, one at least. Boxes are proportional to the entire screen as shown in the picture above. To ensure a high level of visual comfort, we customize the typography inside of the box based on the box unit.
## Outline
In the grid system, we define the frame outside the information area based on `row` and `column`, to ensure that every area can have stable arrangement.
Following is a brief look at how it works:
- Establish a set of `column` in the horizontal space defined by `row` (abbreviated col).
- Your content elements should be placed directly in the `col`, and only `col` should be placed directly in `row`.
- The column grid system is a value of 1-24 to represent its range spans. For example, three columns of equal width can be created by ` `.
- If the sum of `col` spans in a `row` are more than 24, then the overflowing `col` as a whole will start a new line arrangement.
Our grid systems base on Flex layout to allow the elements within the parent to be aligned horizontally - left, center, right, wide arrangement, and decentralized arrangement. The Grid system also supports vertical alignment - top aligned, vertically centered, bottom-aligned. You can also define the order of elements by using `order`.
Layout uses a 24 grid layout to define the width of each "box", but does not rigidly adhere to the grid layout.
## Examples
### Basic Grid
From the stack to the horizontal arrangement.
You can create a basic grid system by using a single set of `Row` and `Col` grid assembly, all of the columns (Col) must be placed in `Row`.
```tsx
import React from 'react';
import { Col, Row } from 'antd';
const App: React.FC = () => (
<>
col
col-12
col-12
col-8
col-8
col-8
col-6
col-6
col-6
col-6
>
);
export default App;
```
### Grid Gutter
You can use the `gutter` property of `Row` as grid spacing, we recommend set it to `(16 + 8n) px` (`n` stands for natural number).
You can set it to a object like `{ xs: 8, sm: 16, md: 24, lg: 32 }` for responsive design.
You can use an array to set vertical spacing, `[horizontal, vertical]` `[16, { xs: 8, sm: 16, md: 24, lg: 32 }]`.
You can set `gutter` to a [string CSS units](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Values_and_Units), for example: `px`、`rem`、`vw`、`vh` etc.
> vertical gutter was supported after `3.24.0`. string type was supported after `5.28.0`.
```css
.gutter-box {
padding: 8px 0;
background: #00a0e9;
}
```
```tsx
import React from 'react';
import { Col, Divider, Row } from 'antd';
const style: React.CSSProperties = { background: '#0092ff', padding: '8px 0' };
const App: React.FC = () => (
<>
Horizontal
col-6
col-6
col-6
col-6
Responsive
col-6
col-6
col-6
col-6
Vertical
col-6
col-6
col-6
col-6
col-6
col-6
col-6
col-6
Gutter(string)
col-6
col-6
col-6
col-6
>
);
export default App;
```
### Column offset
`offset` can set the column to the right side. For example, using `offset = {4}` can set the element shifted to the right four columns width.
```tsx
import React from 'react';
import { Col, Row } from 'antd';
const App: React.FC = () => (
<>
col-8
col-8
col-6 col-offset-6
col-6 col-offset-6
col-12 col-offset-6
>
);
export default App;
```
### Grid sort
By using `push` and `pull` class you can easily change column order.
```tsx
import React from 'react';
import { Col, Row } from 'antd';
const App: React.FC = () => (
col-18 col-push-6
col-6 col-pull-18
);
export default App;
```
### Typesetting
Child elements depending on the value of the `start`, `center`, `end`, `space-between`, `space-around` and `space-evenly`, which are defined in its parent node typesetting mode.
```css
#grid-demo-flex [class~='ant-row'] {
background: rgba(128, 128, 128, 0.08);
}
```
```tsx
import React from 'react';
import { Col, Divider, Row } from 'antd';
const App: React.FC = () => (
<>
sub-element align left
col-4
col-4
col-4
col-4
sub-element align center
col-4
col-4
col-4
col-4
sub-element align right
col-4
col-4
col-4
col-4
sub-element monospaced arrangement
col-4
col-4
col-4
col-4
sub-element align full
col-4
col-4
col-4
col-4
sub-element align evenly
col-4
col-4
col-4
col-4
>
);
export default App;
```
### Alignment
Child elements vertically aligned.
```css
#grid-demo-flex-align [class~='ant-row'] {
background: rgba(128, 128, 128, 0.08);
}
```
```tsx
import React from 'react';
import { Col, Divider, Row } from 'antd';
const DemoBox: React.FC> = (props) => (
{props.children}
);
const App: React.FC = () => (
<>
Align Top
col-4
col-4
col-4
col-4
Align Middle
col-4
col-4
col-4
col-4
Align Bottom
col-4
col-4
col-4
col-4
>
);
export default App;
```
### Order
To change the element sort by `order`.
```css
#grid-demo-flex-order [class~='ant-row'] {
background: rgba(128, 128, 128, 0.08);
}
```
```tsx
import React from 'react';
import { Col, Divider, Row } from 'antd';
const App: React.FC = () => (
<>
Normal
1 col-order-4
2 col-order-3
3 col-order-2
4 col-order-1
Responsive
1 col-order-responsive
2 col-order-responsive
3 col-order-responsive
4 col-order-responsive
>
);
export default App;
```
### Flex Stretch
Col provides `flex` prop to support fill rest.
```tsx
import React from 'react';
import { Col, Divider, Row } from 'antd';
const App: React.FC = () => (
<>
Percentage columns
2 / 5
3 / 5
Fill rest
100px
Fill Rest
Raw flex style
1 1 200px
0 1 300px
none
auto with no-wrap
>
);
export default App;
```
### Responsive
Referring to the Bootstrap [responsive design](http://getbootstrap.com/css/#grid-media-queries), here preset seven dimensions: `xs` `sm` `md` `lg` `xl` `xxl` `xxxl`.
```tsx
import React from 'react';
import { Col, Row } from 'antd';
const App: React.FC = () => (
Col
Col
Col
);
export default App;
```
### Flex Responsive
Support much more flexible responsive flex ratio, which requires CSS Variables supported by browser.
```tsx
import React from 'react';
import { Col, Row } from 'antd';
const App: React.FC = () => (
{Array.from({ length: 10 }).map((_, index) => {
const key = `col-${index}`;
return (
Col
);
})}
);
export default App;
```
### More responsive
`span` `pull` `push` `offset` `order` property can be embedded into `xs` `sm` `md` `lg` `xl` `xxl` properties to use, where `xs={6}` is equivalent to `xs={{span: 6}}`.
```tsx
import React from 'react';
import { Col, Row } from 'antd';
const App: React.FC = () => (
Col
Col
Col
);
export default App;
```
### Playground
A simple playground for column count and gutter.
```css
#grid-demo-playground [class~='ant-col'] {
background: transparent;
border: 0;
}
#grid-demo-playground [class~='ant-col'] > div {
height: 120px;
font-size: 14px;
line-height: 120px;
background: #0092ff;
border-radius: 4px;
}
#grid-demo-playground pre {
padding: 8px 16px;
font-size: 14px;
background: #f9f9f9;
border-radius: 6px;
}
#grid-demo-playground pre.demo-code {
direction: ltr;
}
#grid-demo-playground .ant-col {
padding: 0;
}
```
```tsx
import React, { useState } from 'react';
import { Col, Row, Slider } from 'antd';
const gutters: Record = {};
const vgutters: Record = {};
const colCounts: Record = {};
[8, 16, 24, 32, 40, 48].forEach((value, i) => {
gutters[i] = value;
});
[8, 16, 24, 32, 40, 48].forEach((value, i) => {
vgutters[i] = value;
});
[2, 3, 4, 6, 8, 12].forEach((value, i) => {
colCounts[i] = value;
});
const App: React.FC = () => {
const [gutterKey, setGutterKey] = useState(1);
const [vgutterKey, setVgutterKey] = useState(1);
const [colCountKey, setColCountKey] = useState(2);
const cols = [];
const colCount = colCounts[colCountKey];
let colCode = '';
for (let i = 0; i < colCount; i++) {
cols.push(
Column
,
);
colCode += ` \n`;
}
return (
<>
Horizontal Gutter (px):
gutters[value as number] }}
/>
Vertical Gutter (px):
vgutters[value as number] }}
/>
Column Count:
colCounts[value as number] }}
/>
{cols}
{cols}
Another Row:
{cols}
{`\n${colCode}\n${colCode}
`}
{`\n${colCode}
`}
>
);
};
export default App;
```
### useBreakpoint Hook
Use `useBreakpoint` Hook provide personalized layout. `xs` only takes effect when the screen match the min width.
```tsx
import React from 'react';
import { Grid, Tag } from 'antd';
const { useBreakpoint } = Grid;
const App: React.FC = () => {
const screens = useBreakpoint();
return (
<>
Current break point:{' '}
{Object.entries(screens)
.filter((screen) => !!screen[1])
.map((screen) => (
{screen[0]}
))}
>
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
If the Ant Design grid layout component does not meet your needs, you can use the excellent layout components of the community:
- [react-flexbox-grid](https://roylee0704.github.io/react-flexbox-grid/)
- [react-blocks](https://github.com/whoisandy/react-blocks/)
### Row
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| align | Vertical alignment | `top` \| `middle` \| `bottom` \| `stretch` \| `{[key in 'xs' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'xxl' \| 'xxxl']: 'top' \| 'middle' \| 'bottom' \| 'stretch'}` | `top` | object: 4.24.0 | × |
| gutter | Spacing between grids, could be a [string CSS units](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Values_and_Units) or a object like { xs: 8, sm: 16, md: 24}. Or you can use array to make horizontal and vertical spacing work at the same time `[horizontal, vertical]` | number \| string \| object \| array | 0 | string: 5.28.0 | × |
| justify | Horizontal arrangement | `start` \| `end` \| `center` \| `space-around` \| `space-between` \| `space-evenly` \| `{[key in 'xs' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'xxl' \| 'xxxl']: 'start' \| 'end' \| 'center' \| 'space-around' \| 'space-between' \| 'space-evenly'}` | `start` | object: 4.24.0 | × |
| wrap | Auto wrap line | boolean | true | 4.8.0 | × |
### Col
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| flex | Flex layout style | string \| number | - | | × |
| offset | The number of cells to offset Col from the left | number | 0 | | × |
| order | Raster order | number | 0 | | × |
| pull | The number of cells that raster is moved to the left | number | 0 | | × |
| push | The number of cells that raster is moved to the right | number | 0 | | × |
| span | Raster number of cells to occupy, 0 corresponds to `display: none` | number | none | | × |
| xs | `screen < 576px` and also default setting, could be a `span` value or an object containing above props | number \| object | - | | × |
| sm | `screen ≥ 576px`, could be a `span` value or an object containing above props | number \| object | - | | × |
| md | `screen ≥ 768px`, could be a `span` value or an object containing above props | number \| object | - | | × |
| lg | `screen ≥ 992px`, could be a `span` value or an object containing above props | number \| object | - | | × |
| xl | `screen ≥ 1200px`, could be a `span` value or an object containing above props | number \| object | - | | × |
| xxl | `screen ≥ 1600px`, could be a `span` value or an object containing above props | number \| object | - | | × |
| xxxl | `screen ≥ 1920px`, could be a `span` value or an object containing above props | number \| object | - | 6.3.0 | × |
You can modify breakpoint values by customizing `screen[XS|SM|MD|LG|XL|XXL|XXXL]` with [theme customization](/docs/react/customize-theme) (since 5.1.0, [sandbox demo](https://codesandbox.io/s/antd-reproduction-template-forked-dlq3r9?file=/index.js)).
The breakpoints of responsive grid follow [BootStrap 4 media queries rules](https://getbootstrap.com/docs/4.0/layout/overview/#responsive-breakpoints) (not including `occasionally part`).
## Design Token
---
## icon
Source: https://ant.design/components/icon.md
---
category: Components
group: General
title: Icon
description: Semantic vector graphics.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*PdAYS7anRpoAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*xEDOTJx2DEkAAAAAAAAAAAAADrJ8AQ/original
---
## How to use
Before using icons, you need to install the [@ant-design/icons](https://github.com/ant-design/ant-design-icons) package:
:::info{title=Tips}
Remember to use `@ant-design/icons@6.x` with `antd@6.x`, see: [#53275](https://github.com/ant-design/ant-design/issues/53275#issuecomment-2747448317)
:::
## List of icons
## Examples
### Basic
Import icons from `@ant-design/icons`, component name of icons with different theme is the icon name suffixed by the theme name. Specify the `spin` property to show the spinning animation.
```tsx
import React from 'react';
import {
HomeOutlined,
LoadingOutlined,
SettingFilled,
SmileOutlined,
SyncOutlined,
} from '@ant-design/icons';
import { Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Two-tone icon and colorful icon
You can set the `twoToneColor` prop to a specific primary color for two-tone icons.
```tsx
import React from 'react';
import { CheckCircleTwoTone, HeartTwoTone, SmileTwoTone } from '@ant-design/icons';
import { Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Custom Icon
Create a reusable React component by using ` `. The property `component` takes a React component that renders to a `svg` element.
```tsx
import React from 'react';
import Icon, { HomeOutlined } from '@ant-design/icons';
import { Space } from 'antd';
import type { GetProps } from 'antd';
type CustomIconComponentProps = GetProps;
const HeartSvg: React.FC = () => (
heart icon
);
const PandaSvg: React.FC = () => (
Panda icon
);
const HeartIcon: React.FC> = (props) => (
);
const PandaIcon: React.FC> = (props) => (
);
const App: React.FC = () => (
);
export default App;
```
### Use iconfont.cn
If you are using [iconfont.cn](https://iconfont.cn/), you can use the icons in your project gracefully.
```tsx
import React from 'react';
import { createFromIconfontCN } from '@ant-design/icons';
import { Space } from 'antd';
const IconFont = createFromIconfontCN({
scriptUrl: '//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js',
});
const App: React.FC = () => (
);
export default App;
```
### Multiple resources from iconfont.cn
You can use `scriptUrl` as an array after `@ant-design/icons@4.1.0`, to manage icons in one ` ` from multiple [iconfont.cn](https://iconfont.cn/) resources. If an icon with a duplicate name is in resources, it will be overridden in array order.
```tsx
import React from 'react';
import { createFromIconfontCN } from '@ant-design/icons';
import { Space } from 'antd';
const IconFont = createFromIconfontCN({
scriptUrl: [
'//at.alicdn.com/t/font_1788044_0dwu4guekcwr.js', // icon-javascript, icon-java, icon-shoppingcart (overridden)
'//at.alicdn.com/t/font_1788592_a5xf2bdic3u.js', // icon-shoppingcart, icon-python
],
});
const App: React.FC = () => (
);
export default App;
```
## API
### Common Icon
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| className | The className of Icon | string | - | | × |
| rotate | Rotate by n degrees (not working in IE9) | number | - | | × |
| spin | Rotate icon with animation | boolean | false | | × |
| style | The style properties of icon, like `fontSize` and `color` | CSSProperties | - | | × |
| twoToneColor | Only supports the two-tone icon. Specify the primary color, or primary and secondary colors | string \| \[string, string] | - | | × |
We still have three different themes for icons, icon component name is the icon name suffixed by the theme name.
```jsx
import { StarOutlined, StarFilled, StarTwoTone } from '@ant-design/icons';
```
### Custom Icon
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| component | The component used for the root node | ComponentType<CustomIconComponentProps> | - | | × |
| rotate | Rotate degrees (not working in IE9) | number | - | | × |
| spin | Rotate icon with animation | boolean | false | | × |
| style | The style properties of icon, like `fontSize` and `color` | CSSProperties | - | | × |
### About SVG icons
We introduced SVG icons in version `3.9.0`, replacing font icons. This has the following benefits:
- Complete offline usage of icons, without dependency on a CDN-hosted font icon file (No more empty square during downloading and no need to deploy icon font files locally either!)
- Much more display accuracy on lower-resolution screens
- The ability to choose icon color
- No need to change built-in icons with overriding styles by providing more props in component
More discussion of SVG icon reference at [#10353](https://github.com/ant-design/ant-design/issues/10353).
> ⚠️ Given the extra bundle size caused by all SVG icons imported in 3.9.0, we will provide a new API to allow developers to import icons as needed, you can track [#12011](https://github.com/ant-design/ant-design/issues/12011) for updates.
>
> While you wait, you can use [webpack plugin](https://github.com/Beven91/webpack-ant-icon-loader) from the community to chunk the icon file.
The properties `theme`, `component` and `twoToneColor` were added in `3.9.0`. The best practice is to pass the property `theme` to every ` ` component.
```jsx
import { MessageOutlined } from '@ant-design/icons';
;
```
All the icons will render to ``. You can still set `style` and `className` for size and color of icons.
```jsx
```
### Set TwoTone Color
When using the two-tone icons, you can use the static methods `getTwoToneColor()` and `setTwoToneColor(colorString)` to specify the primary color.
```jsx
import { getTwoToneColor, setTwoToneColor } from '@ant-design/icons';
setTwoToneColor('#eb2f96');
getTwoToneColor(); // #eb2f96
```
### Custom Font Icon
We added a `createFromIconfontCN` function to help developer use their own icons deployed at [iconfont.cn](https://iconfont.cn/) in a convenient way.
> This method is specified for [iconfont.cn](https://iconfont.cn/).
```jsx
import React from 'react';
import { createFromIconfontCN } from '@ant-design/icons';
import ReactDOM from 'react-dom/client';
const MyIcon = createFromIconfontCN({
scriptUrl: '//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js', // generate in iconfont.cn
});
ReactDOM.createRoot(mountNode).render( );
```
It creates a component that uses SVG sprites in essence.
The following options are available:
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| extraCommonProps | Define extra properties to the component | { \[key: string]: any } | {} | | × |
| scriptUrl | The URL generated by [iconfont.cn](https://iconfont.cn/) project. Support `string[]` after `@ant-design/icons@4.1.0` | string \| string\[] | - | | × |
The property `scriptUrl` should be set to import the SVG sprite symbols.
See [iconfont.cn documents](https://iconfont.cn/help/detail?spm=a313x.7781069.1998910419.15&helptype=code) to learn about how to generate `scriptUrl`.
### Custom SVG Icon
You can import SVG icon as a react component by using `webpack` and [`@svgr/webpack`](https://www.npmjs.com/package/@svgr/webpack). `@svgr/webpack`'s `options` [reference](https://github.com/smooth-code/svgr#options).
```js
// webpack.config.js
module.exports = {
// ... other config
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'babel-loader',
},
{
loader: '@svgr/webpack',
options: {
babel: false,
icon: true,
},
},
],
};
```
You can import SVG icon as a react component by using `vite` and [`vite-plugin-svgr`](https://www.npmjs.com/package/vite-plugin-svgr). `@svgr/webpack`'s `options` [reference](https://github.com/smooth-code/svgr#options).
```js
// vite.config.js
export default defineConfig(() => ({
// ... other config
plugins: [svgr({ svgrOptions: { icon: true } })],
}));
```
```jsx
import React from 'react';
import Icon from '@ant-design/icons';
import MessageSvg from 'path/to/message.svg'; // path to your '*.svg' file.
// import MessageSvg from 'path/to/message.svg?react'; // use vite path to your '*.svg?react' file.
import ReactDOM from 'react-dom/client';
// in create-react-app:
// import { ReactComponent as MessageSvg } from 'path/to/message.svg';
ReactDOM.createRoot(mountNode).render( );
```
The following properties are available for the component:
| Property | Description | Type | Readonly | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| className | The computed class name of the `svg` element | string | - | | × |
| fill | Define the color used to paint the `svg` element | string | `currentColor` | | × |
| height | The height of the `svg` element | string \| number | `1em` | | × |
| style | The computed style of the `svg` element | CSSProperties | - | | × |
| width | The width of the `svg` element | string \| number | `1em` | | × |
## Design Token
## FAQ
### Why does icon style sometimes cause global style error? {#faq-icon-bad-style}
Related issue: [#54391](https://github.com/ant-design/ant-design/issues/54391)
When enable `layer`, icon style may deprioritize `@layer antd` and cause all components to be styled abnormally.
This problem can be resolved by two steps below:
1. use `@ant-design/icons@6.x` with `antd@6.x`.
2. stop to use static methods of `message`, `Modal` and `notification`. use hooks version or `App` provided instance.
If you must use static methods, you can put any of icon components just under `App`, what helps to avoid style impact caused by static methods.
```diff
+ {/* any icon */}
+
{/* your pages */}
```
---
## image
Source: https://ant.design/components/image.md
---
category: Components
group: Data Display
title: Image
description: Preview-able image.
cols: 2
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*FbOCS6aFMeUAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*LVQ3R5JjjJEAAAAAAAAAAAAADrJ8AQ/original
---
## When To Use
- When you need to display pictures.
- Display when loading a large image or fault tolerant handling when loading fail.
## Examples
### Basic Usage
Click the image to zoom in.
```tsx
import React from 'react';
import { Image } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Progressive Loading
Set placeholder via `placeholder` prop. When `placeholder` is `{ progress: true }`, it shows a watercolor ink loading animation; when set to `{ progress: { percent: number } }`, it shows a progress bar; you can also pass a custom React node as placeholder.
```tsx
import React, { useEffect, useState } from 'react';
import { Button, Flex, Image, theme } from 'antd';
const GeneratingProgress: React.FC = () => {
const { token } = theme.useToken();
const [percent, setPercent] = useState(0);
const [status, setStatus] = useState<'idle' | 'generating' | 'complete'>('idle');
const imageStyles = {
root: { borderRadius: token.borderRadiusLG },
image: { borderRadius: token.borderRadiusLG },
cover: { borderRadius: token.borderRadiusLG },
};
useEffect(() => {
if (status === 'generating' && percent < 100) {
const timer = setTimeout(() => {
setPercent((prev) => Math.min(prev + Math.random() * 8 + 2, 100));
}, 200);
return () => clearTimeout(timer);
} else if (status === 'generating' && percent >= 100) {
const timer = setTimeout(() => {
setStatus('complete');
}, 200);
return () => clearTimeout(timer);
}
}, [status, percent]);
const handleStart = () => {
setPercent(0);
setStatus('generating');
};
const imageNode =
status === 'complete' ? (
) : (
(
<>
{progress}
Generating {p}%
>
),
},
}}
/>
);
return (
Generate
{imageNode}
);
};
const App: React.FC = () => {
const { token } = theme.useToken();
const [random, setRandom] = useState(() => Date.now());
const imageStyles = {
root: { borderRadius: token.borderRadiusLG },
image: { borderRadius: token.borderRadiusLG },
cover: { borderRadius: token.borderRadiusLG },
};
return (
<>
'loading...' } }}
/>
(
<>
{progress}
Generating {p}%
>
),
},
}}
/>
{
setRandom(Date.now());
}}
>
Reload Image
}
/>
>
);
};
export default App;
```
### Fault tolerant
Load failed to display image placeholder.
```tsx
import React from 'react';
import { Image } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Multiple image preview
Click the left and right switch buttons to preview multiple images.
```tsx
import React from 'react';
import { Image } from 'antd';
const App: React.FC = () => (
console.log(`current index: ${current}, prev index: ${prev}`),
}}
>
);
export default App;
```
### Preview from one image
Preview a collection from one image.
```tsx
import React from 'react';
import { Image } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Custom preview image
You can set different preview image.
```tsx
import React from 'react';
import { Image } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Controlled Preview
You can make preview controlled.
```tsx
import React, { useState } from 'react';
import { Button, Image, InputNumber } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [scaleStep, setScaleStep] = useState(0.5);
return (
<>
scaleStep:{' '}
setScaleStep(val!)}
/>
setOpen(true)}>
show image preview
{
setOpen(value);
},
}}
/>
>
);
};
export default App;
```
### Custom toolbar render
You can customize the toolbar and add a button for downloading the original image or downloading the flipped and rotated image.
```css
.toolbar-wrapper {
padding: 0px 24px;
color: #fff;
font-size: 20px;
background-color: rgba(0, 0, 0, 0.1);
border-radius: 100px;
}
.toolbar-wrapper .anticon {
padding: 12px;
cursor: pointer;
}
.toolbar-wrapper .anticon[disabled] {
cursor: not-allowed;
opacity: 0.3;
}
.toolbar-wrapper .anticon:hover {
opacity: 0.3;
}
```
```tsx
import React from 'react';
import {
DownloadOutlined,
LeftOutlined,
RightOutlined,
RotateLeftOutlined,
RotateRightOutlined,
SwapOutlined,
UndoOutlined,
ZoomInOutlined,
ZoomOutOutlined,
} from '@ant-design/icons';
import { Image, Space } from 'antd';
const imageList = [
'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
'https://gw.alipayobjects.com/zos/antfincdn/aPkFc8Sj7n/method-draw-image.svg',
];
// you can download flipped and rotated image
// https://codesandbox.io/s/zi-ding-yi-gong-ju-lan-antd-5-7-0-forked-c9jvmp
const App: React.FC = () => {
const [current, setCurrent] = React.useState(0);
// or you can download flipped and rotated image
// https://codesandbox.io/s/zi-ding-yi-gong-ju-lan-antd-5-7-0-forked-c9jvmp
const onDownload = () => {
const url = imageList[current];
const suffix = url.slice(url.lastIndexOf('.'));
const filename = Date.now() + suffix;
fetch(url)
.then((response) => response.blob())
.then((blob) => {
const blobUrl = URL.createObjectURL(new Blob([blob]));
const link = document.createElement('a');
link.href = blobUrl;
link.download = filename;
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(blobUrl);
link.remove();
});
};
return (
(
onActive?.(-1)} />
onActive?.(1)}
/>
),
onChange: (index) => {
setCurrent(index);
},
}}
>
{imageList.map((item, index) => (
))}
);
};
export default App;
```
### Custom preview render
You can customize the preview content.
```tsx
import React from 'react';
import { Image } from 'antd';
const App: React.FC = () => (
(
),
actionsRender: () => null,
}}
src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
/>
);
export default App;
```
### preview mask
mask effect.
```tsx
import React from 'react';
import { Image, Space } from 'antd';
const App: React.FC = () => {
return (
blur
),
}}
/>
Dimmed mask
),
}}
/>
No mask
),
}}
/>
);
};
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Image by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Flex, Image } from 'antd';
import type { GetProp, ImageProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
padding: 4px;
border-radius: 8px;
overflow: hidden;
`,
}));
const styles: ImageProps['styles'] = {
image: {
borderRadius: '4px',
},
};
const stylesFn: ImageProps['styles'] = (info): GetProp => {
if (info.props.preview) {
return {
root: {
border: '2px solid #A594F9',
borderRadius: 8,
padding: 4,
transition: 'all 0.3s ease',
},
image: {
borderRadius: 4,
filter: 'grayscale(50%)',
},
};
}
return {};
};
const App: React.FC = () => {
const sharedProps: ImageProps = {
src: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
width: 160,
alt: '示例图片',
classNames,
};
return (
);
};
export default App;
```
### nested
Nested in the modal
```tsx
import React, { useState } from 'react';
import { Button, Divider, Image, Modal } from 'antd';
const App: React.FC = () => {
const [show1, setShow1] = useState(false);
const [show2, setShow2] = useState(false);
const [show3, setShow3] = useState(false);
return (
<>
{
setShow1(true);
}}
>
showModal
{
setShow1(open);
}}
onCancel={() => {
setShow1(false);
}}
onOk={() => setShow1(false)}
>
{
setShow2(true);
}}
>
test2
{
setShow2(open);
}}
onCancel={() => {
setShow2(false);
}}
onOk={() => setShow2(false)}
>
{
setShow3(true);
}}
>
test3
{
setShow3(open);
}}
onCancel={() => {
setShow3(false);
}}
onOk={() => setShow3(false)}
>
console.log(`current index: ${current}, prev index: ${prev}`),
}}
>
>
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Image
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| alt | Image description | string | - | | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| fallback | Fallback URL when load fails | string | - | | 5.28.0 |
| height | Image height | string \| number | - | | × |
| placeholder | Loading placeholder, supports ReactNode or config object | [PlaceholderType](#placeholdertype) | - | | × |
| preview | Preview configuration; set to false to disable | boolean \| [PreviewType](#previewtype) | true | | `preview.closeIcon`: 5.14.0, `preview.mask`: 6.0.0, `preview.mask.closable`: 6.4.0 |
| src | Image URL | string | - | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| width | Image width | string \| number | - | | × |
| onError | Callback when loading error occurs | (event: Event) => void | - | | × |
Other Property ref [<img>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#Attributes)
### PlaceholderType
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| progress | Progress config, set to `true` to show gradient animation, set `{ percent: number }` to show progress, `render` for custom rendering | boolean \| [ImageProgressConfig](#imageprogressconfig) | - | |
### ImageProgressConfig
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| percent | Progress value | number | - | |
| render | Custom rendering, receives default progress UI and percentage | (progress: React.ReactNode, percent: number) => React.ReactNode | - | |
### PreviewType
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| actionsRender | Custom toolbar render | (originalNode: React.ReactElement, info: ToolbarRenderInfoType) => React.ReactNode | - | |
| closeIcon | Custom close icon | React.ReactNode | - | |
| cover | Custom preview mask | React.ReactNode \| [CoverConfig](#coverconfig) | - | CoverConfig support after v6.0 |
| focusTrap | Whether to trap focus within the preview when open | boolean | true | 6.4.0 |
| ~~destroyOnClose~~ | Destroy child elements on preview close (removed, no longer supported) | boolean | false | |
| ~~forceRender~~ | Force render preview image (removed, no longer supported) | boolean | - | |
| getContainer | Specify container for preview mounting; still full screen; false mounts at current location | string \| HTMLElement \| (() => HTMLElement) \| false | - | |
| imageRender | Custom preview content | (originalNode: React.ReactElement, info: { transform: [TransformType](#transformtype), image: [ImgInfo](#imginfo) }) => React.ReactNode | - | |
| mask | preview mask effect | boolean \| { enabled?: boolean, blur?: boolean, closable?: boolean } | true | mask.closable: 6.4.0 |
| ~~maskClassName~~ | Thumbnail mask class name; please use 'classNames.cover' instead | string | - | |
| maxScale | Maximum zoom scale | number | 50 | |
| minScale | Minimum zoom scale | number | 1 | |
| movable | Whether the preview image can be dragged when it is larger than the viewport | boolean | true | |
| open | Whether to display preview | boolean | - | |
| rootClassName | Root DOM class name for preview; applies to both image and preview wrapper | string | - | |
| scaleStep | Each step's zoom multiplier is 1 + scaleStep | number | 0.5 | |
| src | Custom preview src | string | - | |
| styles | Custom semantic structure styles | Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| ~~toolbarRender~~ | Custom toolbar; please use 'actionsRender' instead | (originalNode: React.ReactElement, info: Omit) => React.ReactNode | - | |
| ~~visible~~ | Whether to show; please use 'open' instead | boolean | - | |
| onOpenChange | Callback when preview open state changes | (visible: boolean) => void | - | |
| onTransform | Callback for preview transform changes | { transform: [TransformType](#transformtype), action: [TransformAction](#transformaction) } | - | |
| ~~onVisibleChange~~ | Callback when 'visible' changes; please use 'onOpenChange' instead | (visible: boolean, prevVisible: boolean) => void | - | |
### PreviewGroup
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| fallback | Fallback URL for load error | string | - | |
| items | Array of preview items | string[] \| { src: string, crossOrigin: string, ... }[] | - | |
| preview | Preview configuration; disable by setting to false | boolean \| [PreviewGroupType](#previewgrouptype) | true | |
### PreviewGroupType
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| actionsRender | Custom toolbar render | (originalNode: React.ReactElement, info: ToolbarRenderInfoType) => React.ReactNode | - | |
| closeIcon | Custom close icon | React.ReactNode | - | |
| countRender | Custom preview count render | (current: number, total: number) => React.ReactNode | - | |
| focusTrap | Whether to trap focus within the preview when open | boolean | true | 6.4.0 |
| current | Index of the current preview image | number | - | |
| ~~forceRender~~ | Force render preview image (removed, no longer supported) | boolean | - | |
| getContainer | Specify container for preview mounting; still full screen; false mounts at current location | string \| HTMLElement \| (() => HTMLElement) \| false | - | |
| imageRender | Custom preview content | (originalNode: React.ReactElement, info: { transform: [TransformType](#transformtype), image: [ImgInfo](#imginfo), current: number }) => React.ReactNode | - | |
| mask | preview mask effect | boolean \| { enabled?: boolean, blur?: boolean, closable?: boolean } | true | mask.closable: 6.4.0 |
| ~~maskClassName~~ | Thumbnail mask class name; please use 'classNames.cover' instead | string | - | |
| minScale | Minimum zoom scale | number | 1 | |
| maxScale | Maximum zoom scale | number | 50 | |
| movable | Whether the preview image can be dragged when it is larger than the viewport | boolean | true | |
| open | Whether to display preview | boolean | - | |
| ~~rootClassName~~ | Root DOM class name for preview; applies to both image and preview wrapper. Use 'classNames.root' instead | string | - | |
| styles | Custom semantic structure styles | Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| scaleStep | Each step's zoom multiplier is 1 + scaleStep | number | 0.5 | |
| ~~toolbarRender~~ | Custom toolbar; please use 'actionsRender' instead | (originalNode: React.ReactElement, info: ToolbarRenderInfoType) => React.ReactNode | - | |
| ~~visible~~ | Whether to show; please use 'open' instead | boolean | - | |
| onOpenChange | Callback when preview open state changes, includes current preview index | (visible: boolean, info: { current: number }) => void | - | |
| onChange | Callback when changing preview image | (current: number, prevCurrent: number) => void | - | |
| onTransform | Callback for preview transform changes | { transform: [TransformType](#transformtype), action: [TransformAction](#transformaction) } | - | |
| ~~onVisibleChange~~ | Callback when 'visible' changes; please use 'onOpenChange' instead | (visible: boolean, prevVisible: boolean, current: number) => void | - | |
## Interface
### TransformType
```typescript
{
x: number;
y: number;
rotate: number;
scale: number;
flipX: boolean;
flipY: boolean;
}
```
### TransformAction
```typescript
type TransformAction =
| 'flipY'
| 'flipX'
| 'rotateLeft'
| 'rotateRight'
| 'zoomIn'
| 'zoomOut'
| 'close'
| 'prev'
| 'next'
| 'wheel'
| 'doubleClick'
| 'move'
| 'dragRebound';
```
### ToolbarRenderInfoType
```typescript
{
icons: {
flipYIcon: React.ReactNode;
flipXIcon: React.ReactNode;
rotateLeftIcon: React.ReactNode;
rotateRightIcon: React.ReactNode;
zoomOutIcon: React.ReactNode;
zoomInIcon: React.ReactNode;
};
actions: {
onActive?: (index: number) => void; // support after 5.21.0
onFlipY: () => void;
onFlipX: () => void;
onRotateLeft: () => void;
onRotateRight: () => void;
onZoomOut: () => void;
onZoomIn: () => void;
onReset: () => void; // support after 5.17.3
onClose: () => void;
};
transform: TransformType,
current: number;
image: ImgInfo
}
```
### ImgInfo
```typescript
{
url: string;
alt: string;
width: string | number;
height: string | number;
}
```
### CoverConfig
```typescript
type CoverConfig = {
coverNode?: React.ReactNode; // The custom node of preview mask
placement?: 'top' | 'bottom' | 'center'; // Set the position of the preview mask display.
};
```
## Semantic DOM
https://ant.design/components/image/semantic.md
## Design Token
## Component Token (Image)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| previewOperationColor | Color of preview operation icon | string | rgba(255,255,255,0.65) |
| previewOperationColorDisabled | Disabled color of preview operation icon | string | rgba(255,255,255,0.25) |
| previewOperationHoverColor | Color of hovered preview operation icon | string | rgba(255,255,255,0.85) |
| previewOperationSize | Size of preview operation icon | number | 18 |
| progressAnimationDuration | Base duration of loading animation | string | 3s |
| zIndexPopup | z-index of preview popup | number | 1080 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusXS | XS size border radius, used in some small border radius components, such as Segmented, Arrow and other components with small border radius. | number | |
| colorBgBase | Used to derive the base variable of the background color gradient. In v5, we added a layer of background color derivation algorithm to produce map token of background color. But PLEASE DO NOT USE this Seed Token directly in the code! | string | |
| colorBgContainerDisabled | Control the background color of container in disabled state. | string | |
| colorBgMask | The background color of the mask, used to cover the content below the mask, Modal, Drawer, Image and other components use this token | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorTextLightSolid | Control the highlight color of text with background color, such as the text in Primary Button components. | string | |
| colorTextSecondary | The second level of text color is generally used in scenarios where text color is not emphasized, such as label text, menu text selection state, etc. | string | |
| controlHeightLG | LG component height | number | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| margin | Control the margin of an element, with a medium size. | number | |
| marginSM | Control the margin of an element, with a medium-small size. | number | |
| marginXL | Control the margin of an element, with an extra-large size. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseInOut | Preset motion curve. | string | |
| motionEaseOut | Preset motion curve. | string | |
| paddingLG | Control the large padding of the element. | number | |
| paddingSM | Control the small padding of the element. | number | |
---
## input
Source: https://ant.design/components/input.md
---
category: Components
group: Data Entry
title: Input
description: Through mouse or keyboard input content, it is the most basic form field wrapper.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*Y3R0RowXHlAAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*sBqqTatJ-AkAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
- A user input in a form field is needed.
- A search input is required.
## Examples
### Basic usage
Basic usage example.
```tsx
import React from 'react';
import { Input } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Three sizes of Input
There are three sizes of an Input box: `large` (40px), `medium` (32px) and `small` (24px).
```tsx
import React from 'react';
import { UserOutlined } from '@ant-design/icons';
import { Flex, Input } from 'antd';
const App: React.FC = () => (
} />
} />
} />
);
export default App;
```
### Variants
Variants of Input, there are four variants: `outlined` `filled` `borderless` and `underlined`.
```tsx
import React from 'react';
import { Flex, Input } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Compact Style
Use Space.Compact create compact style, See the [Space.Compact](/components/space#spacecompact) documentation for more.
```tsx
import React from 'react';
import { SearchOutlined } from '@ant-design/icons';
import { Button, Input, Select, Space } from 'antd';
const { Search } = Input;
const options = [
{
value: 'zhejiang',
label: 'Zhejiang',
},
{
value: 'jiangsu',
label: 'Jiangsu',
},
];
const App: React.FC = () => (
https://
Submit
);
export default App;
```
### Search box
Example of creating a search box by grouping a standard input with a search button.
```tsx
import React from 'react';
import { AudioOutlined } from '@ant-design/icons';
import { Input, Space } from 'antd';
import type { GetProps } from 'antd';
type SearchProps = GetProps;
const { Search } = Input;
const suffix = ;
const onSearch: SearchProps['onSearch'] = (value, _e, info) => console.log(info?.source, value);
const App: React.FC = () => (
https://
);
export default App;
```
### Search box with loading
Search loading when onSearch.
```tsx
import React from 'react';
import { Input } from 'antd';
const { Search } = Input;
const App: React.FC = () => (
<>
>
);
export default App;
```
### TextArea
For multi-line input.
```tsx
import React from 'react';
import { Input } from 'antd';
const { TextArea } = Input;
const App: React.FC = () => (
<>
>
);
export default App;
```
### Autosizing the height to fit the content
`autoSize` prop for a `textarea` type of `Input` makes the height to automatically adjust based on the content. An option object can be provided to `autoSize` to specify the minimum and maximum number of lines the textarea will automatically adjust.
```tsx
import React, { useState } from 'react';
import { Input } from 'antd';
const { TextArea } = Input;
const App: React.FC = () => {
const [value, setValue] = useState('');
return (
<>
,
Submit
,
Search on Google
,
]}
>
Some contents...
Some contents...
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### mask
mask effect.
```tsx
import React from 'react';
import { Button, Modal, Space } from 'antd';
const modalConfig = {
title: 'Title',
content: 'Some contents...',
};
const App: React.FC = () => {
const [modal, contextHolder] = Modal.useModal();
return (
<>
{
modal.confirm({ ...modalConfig, mask: { blur: true } });
}}
>
blur
{
modal.confirm(modalConfig);
}}
>
Dimmed mask
{
modal.confirm({ ...modalConfig, mask: false });
}}
>
No mask
{contextHolder}
>
);
};
export default App;
```
### Loading
Set the loading status of Modal.
```tsx
import React from 'react';
import { Button, Modal } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = React.useState(false);
const [loading, setLoading] = React.useState(true);
const showLoading = () => {
setOpen(true);
setLoading(true);
// Simple loading mock. You should add cleanup logic in real world.
setTimeout(() => {
setLoading(false);
}, 2000);
};
return (
<>
Open Modal
Loading Modal}
footer={
Reload
}
loading={loading}
open={open}
onCancel={() => setOpen(false)}
>
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### Customized Footer render function
Customize the footer rendering function to support extensions on top of the original.
```tsx
import React, { useState } from 'react';
import { Button, Modal, Space } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showModal = () => {
setOpen(true);
};
const handleOk = () => {
setOpen(false);
};
const handleCancel = () => {
setOpen(false);
};
return (
<>
Open Modal
{
Modal.confirm({
title: 'Confirm',
content: 'Bla bla ...',
footer: (_, { OkBtn, CancelBtn }) => (
<>
Custom Button
>
),
});
}}
>
Open Modal Confirm
(
<>
Custom Button
>
)}
>
Some contents...
Some contents...
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### Use hooks to get context
Use `Modal.useModal` to get `contextHolder` with context accessible issue. Only hooks method support Promise `await` operation.
```tsx
import React, { createContext } from 'react';
import { Button, Modal, Space } from 'antd';
const ReachableContext = createContext(null);
const UnreachableContext = createContext(null);
const config = {
title: 'Use Hook!',
content: (
<>
{(name) => `Reachable: ${name}!`}
{(name) => `Unreachable: ${name}!`}
>
),
};
const App: React.FC = () => {
const [modal, contextHolder] = Modal.useModal();
return (
{
const confirmed = await modal.confirm(config);
console.log('Confirmed: ', confirmed);
}}
>
Confirm
{
modal.warning(config);
}}
>
Warning
{
modal.info(config);
}}
>
Info
{
modal.error(config);
}}
>
Error
{/* `contextHolder` should always be placed under the context you want to access */}
{contextHolder}
{/* Can not access this context since `contextHolder` is not in it */}
);
};
export default App;
```
### Internationalization
To customize the text of the buttons, you need to set `okText` and `cancelText` props.
```tsx
import React, { useState } from 'react';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Modal, Space } from 'antd';
const LocalizedModal = () => {
const [open, setOpen] = useState(false);
const showModal = () => {
setOpen(true);
};
const hideModal = () => {
setOpen(false);
};
return (
<>
Modal
Bla bla ...
Bla bla ...
Bla bla ...
>
);
};
const App: React.FC = () => {
const [modal, contextHolder] = Modal.useModal();
const confirm = () => {
modal.confirm({
title: 'Confirm',
icon: ,
content: 'Bla bla ...',
okText: '确认',
cancelText: '取消',
});
};
return (
<>
Confirm
{contextHolder}
>
);
};
export default App;
```
### Manual to update destroy
Manually updating and destroying a modal through instance.
```tsx
import React from 'react';
import { Button, Modal } from 'antd';
const App: React.FC = () => {
const [modal, contextHolder] = Modal.useModal();
const countDown = () => {
let secondsToGo = 5;
const instance = modal.success({
title: 'This is a notification message',
content: `This modal will be destroyed after ${secondsToGo} second.`,
});
const timer = setInterval(() => {
secondsToGo -= 1;
instance.update({
content: `This modal will be destroyed after ${secondsToGo} second.`,
});
}, 1000);
setTimeout(() => {
clearInterval(timer);
instance.destroy();
}, secondsToGo * 1000);
};
return (
<>
Open modal to close in 5s
{contextHolder}
>
);
};
export default App;
```
### To customize the position of modal
You can use `centered`,`style.top` or other styles to set position of modal dialog.
```tsx
import React, { useState } from 'react';
import { Button, Modal } from 'antd';
const App: React.FC = () => {
const [modal1Open, setModal1Open] = useState(false);
const [modal2Open, setModal2Open] = useState(false);
return (
<>
setModal1Open(true)}>
Display a modal dialog at 20px to Top
setModal1Open(false)}
onCancel={() => setModal1Open(false)}
>
some contents...
some contents...
some contents...
setModal2Open(true)}>
Vertically centered modal dialog
setModal2Open(false)}
onCancel={() => setModal2Open(false)}
>
some contents...
some contents...
some contents...
>
);
};
export default App;
```
### Customize footer buttons props
Passing `okButtonProps` and `cancelButtonProps` will customize the OK button and cancel button props.
```tsx
import React, { useState } from 'react';
import { Button, Modal } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showModal = () => {
setOpen(true);
};
const handleOk = () => {
setOpen(false);
};
const handleCancel = () => {
setOpen(false);
};
return (
<>
Open Modal with customized button props
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### Custom modal content render
Custom modal content render. use `react-draggable` implements draggable.
```tsx
import React, { useRef, useState } from 'react';
import { Button, Modal } from 'antd';
import type { DraggableData, DraggableEvent } from 'react-draggable';
import Draggable from 'react-draggable';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [disabled, setDisabled] = useState(true);
const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 });
const draggleRef = useRef(null!);
const showModal = () => {
setOpen(true);
};
const handleOk = () => {
setOpen(false);
};
const handleCancel = () => {
setOpen(false);
};
const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
const { clientWidth, clientHeight } = window.document.documentElement;
const targetRect = draggleRef.current?.getBoundingClientRect();
if (!targetRect) {
return;
}
setBounds({
left: -targetRect.left + uiData.x,
right: clientWidth - (targetRect.right - uiData.x),
top: -targetRect.top + uiData.y,
bottom: clientHeight - (targetRect.bottom - uiData.y),
});
};
return (
<>
Open Draggable Modal
{
if (disabled) {
setDisabled(false);
}
}}
onMouseOut={() => {
setDisabled(true);
}}
// fix eslintjsx-a11y/mouse-events-have-key-events
// https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/mouse-events-have-key-events.md
onFocus={() => {}}
onBlur={() => {}}
// end
>
Draggable Modal
}
open={open}
onOk={handleOk}
onCancel={handleCancel}
modalRender={(modal) => (
onStart(event, uiData)}
>
{modal}
)}
>
Just don't learn physics at school and your life will be full of magic and miracles.
Day before yesterday I saw a rabbit, and yesterday a deer, and today, you.
>
);
};
export default App;
```
### To customize the width of modal
Use `width` to set the width of the modal dialog.
```tsx
import React, { useState } from 'react';
import { Button, Flex, Modal } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [openResponsive, setOpenResponsive] = useState(false);
return (
{/* Basic */}
setOpen(true)}>
Open Modal of 1000px width
setOpen(false)}
onCancel={() => setOpen(false)}
width={1000}
>
some contents...
some contents...
some contents...
{/* Responsive */}
setOpenResponsive(true)}>
Open Modal of responsive width
setOpenResponsive(false)}
onCancel={() => setOpenResponsive(false)}
width={{
xs: '90%',
sm: '80%',
md: '70%',
lg: '60%',
xl: '50%',
xxl: '40%',
}}
>
some contents...
some contents...
some contents...
);
};
export default App;
```
### Static Method
Static methods cannot consume Context provided by `ConfigProvider`. When enable `layer`, they may also cause style errors. Please use hooks version or `App` provided instance first.
```tsx
import React from 'react';
import { Button, Modal, Space } from 'antd';
const info = () => {
Modal.info({
title: 'This is a notification message',
content: (
some messages...some messages...
some messages...some messages...
),
onOk() {},
});
};
const success = () => {
Modal.success({
content: 'some messages...some messages...',
});
};
const error = () => {
Modal.error({
title: 'This is an error message',
content: 'some messages...some messages...',
});
};
const warning = () => {
Modal.warning({
title: 'This is a warning message',
content: 'some messages...some messages...',
});
};
const App: React.FC = () => (
Info
Success
Error
Warning
);
export default App;
```
### Static confirmation
Use `confirm()` to show a confirmation modal dialog. Let onCancel/onOk function return a promise object to delay closing the dialog.
```tsx
import React from 'react';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { Button, Modal, Space } from 'antd';
const { confirm } = Modal;
const showConfirm = () => {
confirm({
title: 'Do you want to delete these items?',
icon: ,
content: 'Some descriptions',
onOk() {
console.log('OK');
},
onCancel() {
console.log('Cancel');
},
});
};
const showPromiseConfirm = () => {
confirm({
title: 'Do you want to delete these items?',
icon: ,
content: 'When clicked the OK button, this dialog will be closed after 1 second',
onOk() {
return new Promise((resolve, reject) => {
setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
}).catch(() => console.log('Oops errors!'));
},
onCancel() {},
});
};
const showDeleteConfirm = () => {
confirm({
title: 'Are you sure delete this task?',
icon: ,
content: 'Some descriptions',
okText: 'Yes',
okType: 'danger',
cancelText: 'No',
onOk() {
console.log('OK');
},
onCancel() {
console.log('Cancel');
},
});
};
const showPropsConfirm = () => {
confirm({
title: 'Are you sure delete this task?',
icon: ,
content: 'Some descriptions',
okText: 'Yes',
okType: 'danger',
okButtonProps: {
disabled: true,
},
cancelText: 'No',
onOk() {
console.log('OK');
},
onCancel() {
console.log('Cancel');
},
});
};
const App: React.FC = () => (
Confirm
With promise
Delete
With extra props
);
export default App;
```
### destroy confirmation modal dialog
`Modal.destroyAll()` will destroy all confirmation modal dialogs. Usually, you can use it in router change event to destroy confirm modal dialog automatically.
```tsx
import React from 'react';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Modal } from 'antd';
const { confirm } = Modal;
const destroyAll = () => {
Modal.destroyAll();
};
const showConfirm = () => {
for (let i = 0; i < 3; i += 1) {
setTimeout(() => {
confirm({
icon: ,
content: Click to destroy all ,
onOk() {
console.log('OK');
},
onCancel() {
console.log('Cancel');
},
});
}, i * 500);
}
};
const App: React.FC = () => Confirm ;
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Modal by passing objects or functions through `classNames` and `styles`.
```tsx
import React, { useState } from 'react';
import { Button, Flex, Modal } from 'antd';
import type { GetProp, ModalProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const lineStyle: React.CSSProperties = {
lineHeight: '28px',
};
const sharedContent = (
<>
Following the Ant Design specification, we developed a React UI library antd that contains a
set of high quality components and demos for building rich, interactive user interfaces.
🌈 Enterprise-class UI designed for web applications.
📦 A set of high-quality React components out of the box.
🛡 Written in TypeScript with predictable static types.
⚙️ Whole package of design resources and development tools.
🌍 Internationalization support for dozens of languages.
🎨 Powerful theme customization in every detail.
>
);
const classNames = createStaticStyles(({ css }) => ({
container: css`
border-radius: 10px;
padding: 10px;
`,
}));
const styles: ModalProps['styles'] = {
mask: {
backgroundImage: `linear-gradient(to top, #18181b 0, rgba(21, 21, 22, 0.2) 100%)`,
},
};
const stylesFn: ModalProps['styles'] = (info): GetProp => {
if (info.props.footer) {
return {
container: {
borderRadius: 14,
border: '1px solid #ccc',
padding: 0,
overflow: 'hidden',
},
header: {
padding: 16,
},
body: {
padding: 16,
},
footer: {
padding: '16px 10px',
backgroundColor: '#fafafa',
},
};
}
return {};
};
const App: React.FC = () => {
const [modalOpen, setModalOpen] = useState(false);
const [modalFnOpen, setModalFnOpen] = useState(false);
const sharedProps: ModalProps = {
centered: true,
classNames,
};
const footer: React.ReactNode = (
<>
setModalFnOpen(false)}
styles={{ root: { borderColor: '#ccc', color: '#171717', backgroundColor: '#fff' } }}
>
Cancel
setModalOpen(true)}
>
Submit
>
);
return (
setModalOpen(true)}>Open Style Modal
setModalFnOpen(true)}>
Open Function Modal
setModalOpen(false)}
onCancel={() => setModalOpen(false)}
>
{sharedContent}
setModalFnOpen(false)}
onCancel={() => setModalFnOpen(false)}
>
{sharedContent}
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| afterClose | Specify a function that will be called when modal is closed completely | function | - | | × |
| cancelButtonProps | The cancel button props | [ButtonProps](/components/button/#api) | - | | 6.0.0 |
| cancelText | Text of the Cancel button | ReactNode | `Cancel` | | × |
| centered | Centered Modal | boolean | false | | 5.24.0 |
| classNames | Customize class for each semantic structure inside the Modal component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | | 5.10.0 |
| closable | Whether a close (x) button is visible on top right or not | boolean \| [ClosableType](#closabletype) | true | - | 5.16.0 |
| closeIcon | Custom close icon. 5.7.0: close button will be hidden when setting to `null` or `false` | ReactNode | <CloseOutlined /> | | 5.14.0 |
| confirmLoading | Whether to apply loading visual effect for OK button or not | boolean | false | | × |
| ~~destroyOnClose~~ | Whether to unmount child components on onClose | boolean | false | | × |
| destroyOnHidden | Whether to unmount child components on onClose | boolean | false | 5.25.0 | × |
| ~~focusTriggerAfterClose~~ | Whether need to focus trigger element after dialog is closed. Please use `focusable.focusTriggerAfterClose` instead | boolean | true | 4.9.0 | × |
| footer | Footer content, set as `footer={null}` when you don't need default buttons | ReactNode \| (originNode: ReactNode, extra: { OkBtn: React.FC, CancelBtn: React.FC }) => ReactNode | (OK and Cancel buttons) | renderFunction: 5.9.0 | × |
| forceRender | Force render Modal | boolean | false | | × |
| focusable | Configuration for focus management in the Modal | `{ trap?: boolean, focusTriggerAfterClose?: boolean }` | - | 6.2.0 | 6.4.0 |
| getContainer | The mounted node for Modal but still display at fullscreen | HTMLElement \| () => HTMLElement \| Selectors \| false | document.body | | × |
| keyboard | Whether support press esc to close | boolean | true | | × |
| mask | Mask effect | boolean \| `{enabled?: boolean, blur?: boolean, closable?: boolean}` | true | mask.closable: 6.3.0 | 6.0.0, mask.closable: 6.3.0 |
| ~~maskClosable~~ | Whether to close the modal dialog when the mask (area outside the modal) is clicked. Please use `mask.closable` instead. | boolean | true | - | × |
| modalRender | Custom modal content render | (node: ReactNode) => ReactNode | - | 4.7.0 | × |
| okButtonProps | The ok button props | [ButtonProps](/components/button/#api) | - | | 6.0.0 |
| okText | Text of the OK button | ReactNode | `OK` | | × |
| okType | Button `type` of the OK button | string | `primary` | | × |
| style | Style of floating layer, typically used at least for adjusting the position | CSSProperties | - | | 5.7.0 |
| styles | Customize inline style for each semantic structure inside the Modal component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.10.0 |
| loading | Show the skeleton | boolean | | 5.18.0 | × |
| title | The modal dialog's title | ReactNode | - | | × |
| open | Whether the modal dialog is visible or not | boolean | false | | × |
| width | Width of the modal dialog | string \| number \| [Breakpoint](/components/grid#col) | 520 | Breakpoint: 5.23.0 | × |
| wrapClassName | The class name of the container of the modal dialog | string | - | | × |
| zIndex | The `z-index` of the Modal | number | 1000 | | × |
| onCancel | Specify a function that will be called when a user clicks mask, close button on top right or Cancel button | function(e) | - | | × |
| onOk | Specify a function that will be called when a user clicks the OK button | function(e) | - | | × |
| afterOpenChange | Callback when the animation ends when Modal is turned on and off | (open: boolean) => void | - | 5.4.0 | × |
#### Note
- The state of Modal will be preserved at it's component lifecycle by default, if you wish to open it with a brand new state every time, set `destroyOnHidden` on it.
- There is a situation that using ` ` with Form, which won't clear fields value when closing Modal even you have set `destroyOnHidden`. You need ` ` in this case.
- `Modal.method()` RTL mode only supports hooks.
### Modal.method()
There are five ways to display the information based on the content's nature:
- `Modal.info`
- `Modal.success`
- `Modal.error`
- `Modal.warning`
- `Modal.confirm`
The items listed above are all functions, expecting a settings object as parameter. The properties of the object are follows:
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| afterClose | Specify a function that will be called when modal is closed completely | function | - | 4.9.0 |
| ~~autoFocusButton~~ | Specify which button to autofocus. Please use `focusable.autoFocusButton` instead | null \| `ok` \| `cancel` | `ok` | |
| cancelButtonProps | The cancel button props | [ButtonProps](/components/button/#api) | - | |
| cancelText | Text of the Cancel button with Modal.confirm | string | `Cancel` | |
| centered | Centered Modal | boolean | false | |
| className | The className of container | string | - | |
| closable | Whether a close (x) button is visible on top right of the confirm dialog or not | boolean \| [ClosableType](#closabletype) | false | - |
| closeIcon | Custom close icon | ReactNode | undefined | 4.9.0 |
| content | Content | ReactNode | - | |
| focusable.autoFocusButton | Specify which button to autofocus | null \| `ok` \| `cancel` | `ok` | 6.2.0 |
| footer | Footer content, set as `footer: null` when you don't need default buttons | ReactNode \| (originNode: ReactNode, extra: { OkBtn: React.FC, CancelBtn: React.FC }) => ReactNode | - | renderFunction: 5.9.0 |
| getContainer | Return the mount node for Modal | HTMLElement \| () => HTMLElement \| Selectors \| false | document.body | |
| icon | Custom icon | ReactNode | <ExclamationCircleFilled /> | |
| keyboard | Whether support press esc to close | boolean | true | |
| mask | Mask effect | boolean \| `{enabled?: boolean, blur?: boolean, closable?: boolean}` | true | |
| ~~maskClosable~~ | Whether to close the modal dialog when the mask (area outside the modal) is clicked. Please use `mask.closable` instead. | boolean | false | - |
| okButtonProps | The ok button props | [ButtonProps](/components/button/#api) | - | |
| okText | Text of the OK button | string | `OK` | |
| okType | Button `type` of the OK button | string | `primary` | |
| style | Style of floating layer, typically used at least for adjusting the position | CSSProperties | - | |
| title | Title | ReactNode | - | |
| width | Width of the modal dialog | string \| number | 416 | |
| wrapClassName | The class name of the container of the modal dialog | string | - | 4.18.0 |
| zIndex | The `z-index` of the Modal | number | 1000 | |
| onCancel | Click to onCancel the callback, the parameter is the closing function, if it returns a promise, resolve means normal closing, reject means not closing | function(close) | - | |
| onOk | Click to onOk the callback, the parameter is the closing function, if it returns a promise, resolve means normal closing, reject means not closing | function(close) | - | |
All the `Modal.method`s will return a reference, and then we can update and close the modal dialog by the reference.
### ClosableType
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| afterClose | Specify a function that will be called when modal is closed completely | function | - | - |
| closeIcon | Custom close icon | ReactNode | undefined | - |
| disabled | Whether disabled close icon | boolean | false | - |
| onClose | Trigger when modal close | Function | undefined | - |
```jsx
const modal = Modal.info();
modal.update({
title: 'Updated title',
content: 'Updated content',
});
// on 4.8.0 or above, you can pass a function to update modal
modal.update((prevConfig) => ({
...prevConfig,
title: `${prevConfig.title} (New)`,
}));
modal.destroy();
```
- `Modal.destroyAll`
`Modal.destroyAll()` could destroy all confirmation modal dialogs(`Modal.confirm|success|info|error|warning`). Usually, you can use it in router change event to destroy confirm modal dialog automatically without use modal reference to close( it's too complex to use for all modal dialogs)
```jsx
import { browserHistory } from 'react-router';
// router change
browserHistory.listen(() => {
Modal.destroyAll();
});
```
### Modal.useModal()
When you need using Context, you can use `contextHolder` which created by `Modal.useModal` to insert into children. Modal created by hooks will get all the context where `contextHolder` are. Created `modal` has the same creating function with `Modal.method`.
```jsx
const [modal, contextHolder] = Modal.useModal();
React.useEffect(() => {
modal.confirm({
// ...
});
}, []);
return {contextHolder}
;
```
`modal.confirm` return method:
- `destroy`: Destroy current modal
- `update`: Update current modal
- `then`: (Hooks only) Promise chain call, support `await` operation
```tsx
// Return `true` when click `onOk` and `false` when click `onCancel`
const confirmed = await modal.confirm({ ... });
```
## Semantic DOM
https://ant.design/components/modal/semantic.md
## Design Token
## Component Token (Modal)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| contentBg | Background color of content | string | #ffffff |
| footerBg | Background color of footer | string | transparent |
| headerBg | Background color of header | string | transparent |
| titleColor | Font color of title | string | rgba(0,0,0,0.88) |
| titleFontSize | Font size of title | string \| number | 16 |
| titleLineHeight | Line height of title | string \| number | 1.5 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| boxShadow | Control the box shadow style of an element. | string | |
| colorBgMask | The background color of the mask, used to cover the content below the mask, Modal, Drawer, Image and other components use this token | string | |
| colorBgTextActive | Control the background color of text in active state. | string | |
| colorBgTextHover | Control the background color of text in hover state. | string | |
| colorIcon | Weak action. Such as `allowClear` or Alert close button | string | |
| colorIconHover | Weak action hover color. Such as `allowClear` or Alert close button | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorSplit | Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| controlHeight | The height of the basic controls such as buttons and input boxes in Ant Design | number | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeHeading5 | Font size of h5 tag. | string \| number | |
| fontSizeLG | Large font size | number | |
| fontWeightStrong | Control the font weight of heading components (such as h1, h2, h3) or selected item. | number | |
| lineHeight | Line height of text. | number | |
| lineHeightHeading5 | Line height of h5 tag. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| margin | Control the margin of an element, with a medium size. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseInOutCirc | Preset motion curve. | string | |
| motionEaseOutCirc | Preset motion curve. | string | |
| padding | Control the padding of the element. | number | |
| screenLGMin | Control the minimum width of large screens. | number | |
| screenMDMin | Control the minimum width of medium screens. | number | |
| screenSMMax | Control the maximum width of small screens. | number | |
| screenSMMin | Control the minimum width of small screens. | number | |
| screenXLMin | Control the minimum width of extra large screens. | number | |
| screenXSMin | Control the minimum width of extra small screens. | number | |
| screenXXLMin | Control the minimum width of extra extra large screens. | number | |
| screenXXXLMin | Control the minimum width of XXXL screens. | number | |
| zIndexPopupBase | Base zIndex of component like FloatButton, Affix which can be cover by large popup | number | |
## FAQ
### Why content not update when Modal closed? {#faq-content-not-update}
Modal will use memo to avoid content jumping when closed. Also, if you use Form in Modal, you can reset `initialValues` by calling `resetFields` in effect.
### Why I can not access context, redux, ConfigProvider `locale/prefixCls` in Modal.xxx? {#faq-context-redux}
antd will dynamic create React instance by `ReactDOM.render` when call Modal methods. Whose context is different with origin code located context.
When you need context info (like ConfigProvider context), you can use `Modal.useModal` to get `modal` instance and `contextHolder` node. And put it in your children:
```tsx
const [modal, contextHolder] = Modal.useModal();
// then call modal.confirm instead of Modal.confirm
return (
{/* contextHolder is in Context1, which means modal will get context of Context1 */}
{contextHolder}
{/* contextHolder is out of Context2, which means modal will not get context of Context2 */}
);
```
**Note:** You must insert `contextHolder` into your children with hooks. You can use origin method if you do not need context connection.
> [App Package Component](/components/app) can be used to simplify the problem of `useModal` and other methods that need to manually implant contextHolder.
### How to set static methods prefixCls ? {#faq-set-prefix-cls}
You can config with [`ConfigProvider.config`](/components/config-provider#configproviderconfig-4130)
---
## notification
Source: https://ant.design/components/notification.md
---
category: Components
group: Feedback
noinstant: true
title: Notification
description: Prompt notification message globally.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*cRmqTY4nKPEAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*W3RmSov-xVMAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
To display a notification message at any of the four corners of the viewport. Typically it can be used in the following cases:
- A notification with complex content.
- A notification providing a feedback based on the user interaction. Or it may show some details about upcoming steps the user may have to follow.
- A notification that is pushed by the application.
## Examples
### Hooks usage (recommended)
Use `notification.useNotification` to get `contextHolder` with context accessible issue. Please note that, we recommend to use top level registration instead of `notification` static method, because static method cannot consume context, and ConfigProvider data will not work.
```tsx
import React, { useMemo } from 'react';
import {
RadiusBottomleftOutlined,
RadiusBottomrightOutlined,
RadiusUpleftOutlined,
RadiusUprightOutlined,
} from '@ant-design/icons';
import { Button, Divider, notification, Space } from 'antd';
import type { NotificationArgsProps } from 'antd';
type NotificationPlacement = NotificationArgsProps['placement'];
const Context = React.createContext({ name: 'Default' });
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = (placement: NotificationPlacement) => {
api.info({
title: `Notification ${placement}`,
description: {({ name }) => `Hello, ${name}!`} ,
placement,
});
};
const contextValue = useMemo(() => ({ name: 'Ant Design' }), []);
return (
{contextHolder}
openNotification('topLeft')}
icon={ }
>
topLeft
openNotification('topRight')}
icon={ }
>
topRight
openNotification('bottomLeft')}
icon={ }
>
bottomLeft
openNotification('bottomRight')}
icon={ }
>
bottomRight
);
};
export default App;
```
### Duration after which the notification box is closed
`Duration` can be used to specify how long the notification stays open. After the duration time elapses, the notification closes automatically. If not specified, default value is 4.5 seconds. If you set the value to 0, the notification box will never close automatically.
```tsx
import React from 'react';
import { Button, notification } from 'antd';
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = () => {
api.open({
title: 'Notification Title',
description:
'I will never close automatically. This is a purposely very very long description that has many many characters and words.',
duration: 0,
});
};
return (
<>
{contextHolder}
Open the notification box
>
);
};
export default App;
```
### Notification with icon
A notification box with a icon at the left side.
```tsx
import React from 'react';
import { Button, Flex, notification } from 'antd';
type NotificationType = 'success' | 'info' | 'warning' | 'error';
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotificationWithIcon = (type: NotificationType) => {
api[type]({
title: 'Notification Title',
description:
'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
});
};
return (
<>
{contextHolder}
openNotificationWithIcon('success')}
>
Success
openNotificationWithIcon('info')}>
Info
openNotificationWithIcon('warning')}
>
Warning
openNotificationWithIcon('error')}>
Error
>
);
};
export default App;
```
### Custom close button
To customize the style or font of the close button.
```tsx
import React from 'react';
import { Button, notification, Space } from 'antd';
const close = () => {
console.log(
'Notification was closed. Either the close button was clicked or duration time elapsed.',
);
};
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = () => {
const key = `open${Date.now()}`;
const btn = (
api.destroy()}>
Destroy All
api.destroy(key)}>
Confirm
);
api.open({
title: 'Notification Title',
description:
'A function will be be called after the notification is closed (automatically after the "duration" time of manually).',
btn,
key,
onClose: close,
});
};
return (
<>
{contextHolder}
Open the notification box
>
);
};
export default App;
```
### Customized Icon
The icon can be customized to any react node.
```tsx
import React from 'react';
import { SmileOutlined } from '@ant-design/icons';
import { Button, notification } from 'antd';
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = () => {
api.open({
title: 'Notification Title',
description:
'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
icon: ,
});
};
return (
<>
{contextHolder}
Open the notification box
>
);
};
export default App;
```
### Placement
A notification box can appear from the `top` `bottom` `topLeft` `topRight` `bottomLeft` or `bottomRight` of the viewport via `placement`.
```tsx
import React from 'react';
import {
BorderBottomOutlined,
BorderTopOutlined,
RadiusBottomleftOutlined,
RadiusBottomrightOutlined,
RadiusUpleftOutlined,
RadiusUprightOutlined,
} from '@ant-design/icons';
import { Button, Divider, notification, Space } from 'antd';
import type { NotificationArgsProps } from 'antd';
type NotificationPlacement = NotificationArgsProps['placement'];
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = (placement: NotificationPlacement) => {
api.info({
title: `Notification ${placement}`,
description:
'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
placement,
});
};
return (
<>
{contextHolder}
openNotification('top')} icon={ }>
top
openNotification('bottom')}
icon={ }
>
bottom
openNotification('topLeft')}
icon={ }
>
topLeft
openNotification('topRight')}
icon={ }
>
topRight
openNotification('bottomLeft')}
icon={ }
>
bottomLeft
openNotification('bottomRight')}
icon={ }
>
bottomRight
>
);
};
export default App;
```
### Update Message Content
Update content with unique key.
```tsx
import React from 'react';
import { Button, notification } from 'antd';
const key = 'updatable';
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = () => {
api.open({
key,
title: 'Notification Title',
description: 'description.',
});
setTimeout(() => {
api.open({
key,
title: 'New Title',
description: 'New description.',
});
}, 1000);
};
return (
<>
{contextHolder}
Open the notification box
>
);
};
export default App;
```
### Stack
Stack configuration, enabled by default. Notifications will be stacked when the amount is over `threshold`. Up to 3 notifications are shown in the collapsed stack.
```tsx
import React, { useMemo } from 'react';
import { Button, Divider, InputNumber, notification, Space, Switch } from 'antd';
const Context = React.createContext({ name: 'Default' });
const App: React.FC = () => {
const [enabled, setEnabled] = React.useState(true);
const [threshold, setThreshold] = React.useState(3);
const [api, contextHolder] = notification.useNotification({
stack: enabled
? {
threshold,
}
: false,
});
const openNotification = () => {
api.open({
title: 'Notification Title',
description: `${Array.from(
{ length: Math.round(Math.random() * 5) + 1 },
() => 'This is the content of the notification.',
).join('\n')}`,
duration: false,
});
};
const contextValue = useMemo(() => ({ name: 'Ant Design' }), []);
return (
{contextHolder}
Enabled:
setEnabled(v)} />
Threshold:
setThreshold(v || 0)}
/>
Open the notification box
);
};
export default App;
```
### Show with progress
Show progress bar for auto-closing notification.
```tsx
import React from 'react';
import { Button, notification, Space } from 'antd';
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = (pauseOnHover: boolean) => () => {
api.open({
title: 'Notification Title',
description:
'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
showProgress: true,
pauseOnHover,
});
};
return (
<>
{contextHolder}
Pause on hover
Don't pause on hover
>
);
};
export default App;
```
### Static Method (deprecated)
Static methods cannot consume Context provided by `ConfigProvider`. When enable `layer`, they may also cause style errors. Please use hooks version or `App` provided instance first.
```tsx
import React from 'react';
import { Button, notification } from 'antd';
const openNotification = () => {
notification.open({
title: 'Notification Title',
description:
'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
onClick: () => {
console.log('Notification Clicked!');
},
});
};
const App: React.FC = () => (
Open the notification box
);
export default App;
```
### Customize progress bar color
Customize the progress bar color by configuring the component token.
```tsx
import React from 'react';
import { Button, ConfigProvider, notification } from 'antd';
import { createStyles } from 'antd-style';
const COLOR_BG = 'linear-gradient(135deg,#6253e1, #04befe)';
const useStyle = createStyles(({ prefixCls, css }) => ({
linearGradientButton: css`
&.${prefixCls}-btn-primary:not([disabled]):not(.${prefixCls}-btn-dangerous) {
> span {
position: relative;
}
&::before {
content: '';
background: ${COLOR_BG};
position: absolute;
inset: -1px;
opacity: 1;
transition: all 0.3s;
border-radius: inherit;
}
&:hover::before {
opacity: 0;
}
}
`,
}));
const App: React.FC = () => {
const { styles } = useStyle();
const [api, contextHolder] = notification.useNotification();
const openNotification = () => {
api.open({
title: 'Customize progress bar color',
description: 'You can use component token to customize the progress bar color',
showProgress: true,
duration: 20,
});
};
return (
{contextHolder}
Show custom progress color
);
};
export default App;
```
### Custom semantic styles
You can customize the [semantic dom](#semantic-dom) style of Notification with `classNames` and `styles`.
```tsx
import React from 'react';
import { Button, notification, Space } from 'antd';
import type { GetProp, NotificationArgsProps } from 'antd';
const defaultStyles: GetProp = {
root: {
backgroundColor: '#f6ffed',
border: '2px solid #95de64',
borderRadius: 16,
boxShadow: '4px 4px 0 #d9f7be',
},
icon: {
color: '#237804',
},
title: {
color: '#237804',
fontWeight: 600,
},
description: {
color: '#3f6600',
},
};
const styleFn: NotificationArgsProps['styles'] = ({
props,
}): GetProp => {
if (props.type === 'error') {
return {
...defaultStyles,
root: {
...defaultStyles.root,
backgroundColor: '#fff2f0',
borderColor: '#ffccc7',
boxShadow: '4px 4px 0 #ffccc7',
},
icon: {
color: '#cf1322',
},
title: {
color: '#cf1322',
},
description: {
color: '#5c0011',
},
};
}
return defaultStyles;
};
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const sharedProps: NotificationArgsProps = {
title: 'Notification Title',
description: 'This is a notification description.',
duration: false,
};
const openDefault = () => {
api.info({
...sharedProps,
styles: defaultStyles,
});
};
const openError = () => {
api.error({
...sharedProps,
type: 'error',
styles: styleFn,
});
};
return (
<>
{contextHolder}
Default Notification
Error Notification
>
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
- `notification.success(config)`
- `notification.error(config)`
- `notification.info(config)`
- `notification.warning(config)`
- `notification.open(config)`
- `notification.destroy(key?: String)`
The properties of config are as follows:
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| actions | Customized button group | ReactNode | - | 5.24.0 | × |
| ~~btn~~ | Customized close button group, please use `actions` instead | ReactNode | - | - | × |
| className | Customized CSS class | string | - | - | 5.7.0 |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| closable | Whether to show the close button | boolean \| [ClosableType](#closabletype) | true | - | × |
| closeIcon | Custom close icon | ReactNode | true | 5.7.0: close button will be hidden when setting to null or false | 5.14.0 |
| description | The content of notification box (required) | ReactNode | - | - | × |
| duration | Time in seconds before Notification is closed. When set to `0` or `false`, it will never be closed automatically | number \| false | 4.5 | - | × |
| showProgress | Show progress bar for auto-closing notification | boolean | | 5.18.0 | × |
| pauseOnHover | keep the timer running or not on hover | boolean | true | 5.18.0 | × |
| icon | Customized icon | ReactNode | - | - | × |
| key | The unique identifier of the Notification | string | - | - | × |
| title | The title of notification box | ReactNode | - | 6.0.0 | × |
| ~~message~~ | The title of notification box (deprecated), please use `title` instead | ReactNode | - | - | × |
| placement | Position of Notification, can be one of `top` \| `topLeft` \| `topRight` \| `bottom` \| `bottomLeft` \| `bottomRight` | string | `topRight` | - | × |
| role | The semantics of notification content recognized by screen readers. The default value is `alert`. When set as the default value, the screen reader will promptly interrupt any ongoing content reading and prioritize the notification content for immediate attention. | `alert \| status` | `alert` | 5.6.0 | × |
| style | Customized inline style | [CSSProperties](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e434515761b36830c3e58a970abf5186f005adac/types/react/index.d.ts#L794) | - | - | 5.7.0 |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| onClick | Specify a function that will be called when the notification is clicked | function | - | - | × |
| onClose | Trigger when notification closed | function | - | - | × |
| props | An object that can contain `data-*`, `aria-*`, or `role` props, to be put on the notification `div`. This currently only allows `data-testid` instead of `data-*` in TypeScript. See https://github.com/microsoft/TypeScript/issues/28960. | Object | - | - | × |
- `notification.useNotification(config)`
The properties of config are as follows:
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| bottom | Distance from the bottom of the viewport, when `placement` is `bottom` `bottomRight` or `bottomLeft` (unit: pixels) | number | 24 | | × |
| closeIcon | Custom close icon | ReactNode | true | 5.7.0: close button will be hidden when setting to null or false | 5.14.0 |
| getContainer | Return the mount node for Notification | () => HTMLNode | () => document.body | | × |
| placement | Position of Notification, can be one of `top` \| `topLeft` \| `topRight` \| `bottom` \| `bottomLeft` \| `bottomRight` | string | `topRight` | | × |
| showProgress | Show progress bar for auto-closing notification | boolean | | 5.18.0 | × |
| pauseOnHover | keep the timer running or not on hover | boolean | true | 5.18.0 | × |
| rtl | Whether to enable RTL mode | boolean | false | | × |
| stack | Notifications will be stacked when amount is over threshold | boolean \| `{ threshold: number }` | `{ threshold: 3 }` | 5.10.0 | × |
| top | Distance from the top of the viewport, when `placement` is `top` `topRight` or `topLeft` (unit: pixels) | number | 24 | | × |
| maxCount | Max Notification show, drop oldest if exceed limit | number | - | 4.17.0 | × |
`notification` also provides a global `config()` method that can be used for specifying the default options. Once this method is used, all the notification boxes will take into account these globally defined options when displaying.
### ClosableType
| Property | Description | Type | Default | Version |
| --------- | ------------------------------- | --------- | --------- | ------- |
| closeIcon | Custom close icon | ReactNode | undefined | - |
| onClose | Trigger when notification close | Function | undefined | - |
### Global configuration
`notification.config(options)`
> When you use `ConfigProvider` for global configuration, the system will automatically start RTL mode by default.(4.3.0+)
>
> When you want to use it alone, you can start the RTL mode through the following settings.
#### notification.config
```js
notification.config({
placement: 'bottomRight',
bottom: 50,
duration: 3,
rtl: true,
});
```
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| bottom | Distance from the bottom of the viewport, when `placement` is `bottom` `bottomRight` or `bottomLeft` (unit: pixels) | number | 24 | |
| closeIcon | Custom close icon | ReactNode | true | 5.7.0: close button will be hidden when setting to null or false |
| duration | Time in seconds before Notification is closed. When set to 0 or null, it will never be closed automatically | number | 4.5 | |
| getContainer | Return the mount node for Notification, but still display at fullScreen | () => HTMLNode | () => document.body | |
| placement | Position of Notification, can be one of `top` `topLeft` `topRight` `bottom` `bottomLeft` `bottomRight` | string | `topRight` | |
| showProgress | Show progress bar for auto-closing notification | boolean | | 5.18.0 |
| pauseOnHover | keep the timer running or not on hover | boolean | true | 5.18.0 |
| rtl | Whether to enable RTL mode | boolean | false | |
| top | Distance from the top of the viewport, when `placement` is `top` `topRight` or `topLeft` (unit: pixels) | number | 24 | |
| maxCount | Max Notification show, drop oldest if exceed limit | number | - | 4.17.0 |
## Semantic DOM
https://ant.design/components/notification/semantic.md
## Design Token
## Component Token (Notification)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorErrorBg | Background color of error notification container | string | |
| colorInfoBg | Background color of info notification container | string | |
| colorSuccessBg | Background color of success notification container | string | |
| colorWarningBg | Background color of warning notification container | string | |
| progressBg | Background color of Notification progress bar | string | linear-gradient(90deg, #69b1ff, #1677ff) |
| width | Width of Notification | string \| number | 384 |
| zIndexPopup | z-index of Notification | number | 2050 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| boxShadow | Control the box shadow style of an element. | string | |
| colorBgElevated | Container background color of the popup layer, in dark mode the color value of this token will be a little brighter than `colorBgContainer`. E.g: modal, pop-up, menu, etc. | string | |
| colorBgTextActive | Control the background color of text in active state. | string | |
| colorBgTextHover | Control the background color of text in hover state. | string | |
| colorError | Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. | string | |
| colorIcon | Weak action. Such as `allowClear` or Alert close button | string | |
| colorIconHover | Weak action hover color. Such as `allowClear` or Alert close button | string | |
| colorInfo | Used to represent the operation information of the Token sequence, such as Alert, Tag, Progress, and other components use these map tokens. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorSuccess | Used to represent the token sequence of operation success, such as Result, Progress and other components will use these map tokens. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextHeading | Control the font color of heading. | string | |
| colorWarning | Used to represent the warning map token, such as Notification, Alert, etc. Alert or Control component(like Input) will use these map tokens. | string | |
| controlHeightLG | LG component height | number | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeLG | Large font size | number | |
| lineHeight | Line height of text. | number | |
| lineHeightLG | Line height of large text. | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| margin | Control the margin of an element, with a medium size. | number | |
| marginLG | Control the margin of an element, with a large size. | number | |
| marginSM | Control the margin of an element, with a medium-small size. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| marginXXL | Control the margin of an element, with the largest size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseInOut | Preset motion curve. | string | |
| paddingContentHorizontalLG | Control the horizontal padding of content element, suitable for large screen devices. | number | |
| paddingLG | Control the large padding of the element. | number | |
| paddingMD | Control the medium padding of the element. | number | |
## FAQ
### Why I can not access context, redux, ConfigProvider `locale/prefixCls/theme` in notification? {#faq-context-redux}
When you call notification methods, antd dynamically creates a React instance using `ReactDOM.render`, which runs in a different execution context than your original code.
When you need context info (like ConfigProvider context), you can use `notification.useNotification` to get `api` instance and `contextHolder` node. And put it in your children:
```tsx
const [api, contextHolder] = notification.useNotification();
return (
{/* contextHolder is inside Context1 which means api will get value of Context1 */}
{contextHolder}
{/* contextHolder is outside Context2 which means api will **not** get value of Context2 */}
);
```
**Note:** You must insert `contextHolder` into your children with hooks. You can use origin method if you do not need context connection.
> [App wrapper component](/components/app) can be used to simplify the problem of `useNotification` and other methods that need to manually implant contextHolder.
### How to set static methods prefixCls ? {#faq-set-prefix-cls}
You can config with [`ConfigProvider.config`](/components/config-provider#configproviderconfig-4130)
---
## overview
Source: https://ant.design/components/overview.md
---
category: Components
title: Components Overview
showImport: false
---
`antd` provides plenty of UI components to enrich your web applications, and we will improve components experience consistently. We also recommend some great [Third-Party Libraries](/docs/react/recommendation) additionally.
---
## pagination
Source: https://ant.design/components/pagination.md
---
category: Components
group: Navigation
title: Pagination
description: A long list can be divided into several pages, and only one page will be loaded at a time.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*8y_iTJGY_aUAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*WM86SrBC8TsAAAAAAAAAAAAADrJ8AQ/original
---
## When To Use
- When it will take a long time to load/render all items.
- If you want to browse the data by navigating through pages.
## Examples
### Basic
Basic pagination.
```tsx
import React from 'react';
import { Pagination } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Align
```tsx
import React from 'react';
import { Pagination } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### More
More pages.
```tsx
import React from 'react';
import { Pagination } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Changer
Change `pageSize`.
```tsx
import React from 'react';
import type { PaginationProps } from 'antd';
import { Pagination } from 'antd';
const onShowSizeChange: PaginationProps['onShowSizeChange'] = (current, pageSize) => {
console.log(current, pageSize);
};
const App: React.FC = () => (
<>
>
);
export default App;
```
### Jumper
Jump to a page directly.
```tsx
import React from 'react';
import type { PaginationProps } from 'antd';
import { Pagination } from 'antd';
const onChange: PaginationProps['onChange'] = (pageNumber) => {
console.log('Page: ', pageNumber);
};
const App: React.FC = () => (
<>
>
);
export default App;
```
### Size
Small and large size pagination.
```tsx
import React from 'react';
import type { PaginationProps } from 'antd';
import { Divider, Flex, Pagination } from 'antd';
const showTotal: PaginationProps['showTotal'] = (total) => `Total ${total} items`;
const App: React.FC = () => (
Small
Large
);
export default App;
```
### Simple mode
Simple mode.
```tsx
import React from 'react';
import { Pagination } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### Controlled
Controlled page number.
```tsx
import React, { useState } from 'react';
import type { PaginationProps } from 'antd';
import { Pagination } from 'antd';
const App: React.FC = () => {
const [current, setCurrent] = useState(3);
const onChange: PaginationProps['onChange'] = (page) => {
console.log(page);
setCurrent(page);
};
return ;
};
export default App;
```
### Total number
You can show the total number of data by setting `showTotal`.
```tsx
import React from 'react';
import { Pagination } from 'antd';
const App: React.FC = () => (
<>
`Total ${total} items`}
defaultPageSize={20}
defaultCurrent={1}
/>
`${range[0]}-${range[1]} of ${total} items`}
defaultPageSize={20}
defaultCurrent={1}
/>
>
);
export default App;
```
### Show All
Show all configured prop.
```tsx
import React from 'react';
import { Pagination } from 'antd';
const App: React.FC = () => (
`Total ${total} items`}
/>
);
export default App;
```
### Prev and next
Use text link for prev and next button.
```tsx
import React from 'react';
import type { PaginationProps } from 'antd';
import { Pagination } from 'antd';
const itemRender: PaginationProps['itemRender'] = (_, type, originalElement) => {
if (type === 'prev') {
return Previous ;
}
if (type === 'next') {
return Next ;
}
return originalElement;
};
const App: React.FC = () => ;
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Pagination by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Flex, Pagination } from 'antd';
import type { GetProp, PaginationProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
border: 2px dashed #ccc;
padding: 8px;
`,
}));
const styleFn: PaginationProps['styles'] = ({
props,
}): GetProp => {
if (props.size === 'small') {
return {
item: {
backgroundColor: `rgba(200, 200, 200, 0.3)`,
marginInlineEnd: 4,
},
};
}
return {};
};
const App: React.FC = () => {
const paginationSharedProps: PaginationProps = {
total: 500,
classNames: { root: classNames.root },
};
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
```jsx
```
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| align | Align | start \| center \| end | - | 5.19.0 | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| current | Current page number | number | - | | × |
| defaultCurrent | Default initial page number | number | 1 | | × |
| defaultPageSize | Default number of data items per page | number | 10 | | × |
| disabled | Disable pagination | boolean | - | | × |
| hideOnSinglePage | Whether to hide pager on single page | boolean | false | | × |
| itemRender | To customize item's innerHTML | (page, type: 'page' \| 'prev' \| 'next', originalElement) => React.ReactNode | - | | × |
| pageSize | Number of data items per page | number | - | | × |
| pageSizeOptions | Specify the sizeChanger options | number\[] | \[`10`, `20`, `50`, `100`] | | × |
| responsive | If `size` is not specified, `Pagination` would resize according to the width of the window | boolean | - | | × |
| showLessItems | Show less page items | boolean | false | | × |
| showQuickJumper | Determine whether you can jump to pages directly | boolean \| { goButton: ReactNode } | false | | × |
| showSizeChanger | Determine whether to show `pageSize` select | boolean \| [SelectProps](/components/select#api) | - | SelectProps: 5.21.0 | 4.21.0, SelectProps: 5.21.0 |
| showTitle | Show page item's title | boolean | true | | × |
| showTotal | To display the total number and range | function(total, range) | - | | × |
| simple | Whether to use simple mode | boolean \| { readOnly?: boolean } | - | | × |
| size | Component size | `large` \| `medium` \| `small` | `medium` | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| total | Total number of data items | number | 0 | | × |
| totalBoundaryShowSizeChanger | When `total` larger than it, `showSizeChanger` will be true | number | 50 | | 6.2.0 |
| onChange | Called when the page number or `pageSize` is changed, and it takes the resulting page number and pageSize as its arguments | function(page, pageSize) | - | | × |
| onShowSizeChange | Called when `pageSize` is changed | function(current, size) | - | | × |
## Semantic DOM
https://ant.design/components/pagination/semantic.md
## Design Token
## Component Token (Pagination)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| itemActiveBg | Background color of active Pagination item | string | #ffffff |
| itemActiveBgDisabled | Background color of disabled active Pagination item | string | rgba(0,0,0,0.15) |
| itemActiveColor | Text color of active Pagination item | string | #1677ff |
| itemActiveColorDisabled | Text color of disabled active Pagination item | string | rgba(0,0,0,0.25) |
| itemActiveColorHover | Text color of active Pagination item hover | string | #4096ff |
| itemBg | Background color of Pagination item | string | #ffffff |
| itemInputBg | Background color of input | string | #ffffff |
| itemLinkBg | Background color of Pagination item link | string | #ffffff |
| itemSize | Size of Pagination item | number | 32 |
| itemSizeLG | Size of large Pagination item | number | 40 |
| itemSizeSM | Size of small Pagination item | number | 24 |
| miniOptionsSizeChangerTop | Top of Pagination size changer | number | 0 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadius | Border radius of base components | number | |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| colorBgContainer | Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. | string | |
| colorBgContainerDisabled | Control the background color of container in disabled state. | string | |
| colorBgTextActive | Control the background color of text in active state. | string | |
| colorBgTextHover | Control the background color of text in hover state. | string | |
| colorBorder | Default border color, used to separate different elements, such as: form separator, card separator, etc. | string | |
| colorBorderDisabled | Control the border color of the element in the disabled state. | string | |
| colorFillSecondary | The second level of fill color can outline the shape of the element more clearly, such as Rate, Skeleton, etc. It can also be used as the Hover state of the third level of fill color, such as Table, etc. | string | |
| colorFillTertiary | The third level of fill color is used to outline the shape of the element, such as Slider, Segmented, etc. If there is no emphasis requirement, it is recommended to use the third level of fill color as the default fill color. | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorPrimaryHover | Hover state under the main color gradient. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDisabled | Control the color of text in disabled state. | string | |
| colorTextPlaceholder | Control the color of placeholder text. | string | |
| controlHeightLG | LG component height | number | |
| controlOutline | Control the outline color of input component. | string | |
| controlOutlineWidth | Control the outline width of input component. | number | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeSM | Small font size | number | |
| fontWeightStrong | Control the font weight of heading components (such as h1, h2, h3) or selected item. | number | |
| lineHeight | Line height of text. | number | |
| lineHeightLG | Line height of large text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| margin | Control the margin of an element, with a medium size. | number | |
| marginSM | Control the margin of an element, with a medium-small size. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| paddingXXS | Control the extra extra small padding of the element. | number | |
| screenLG | Control the screen width of large screens. | number | |
| screenSM | Control the screen width of small screens. | number | |
---
## popconfirm
Source: https://ant.design/components/popconfirm.md
---
category: Components
group: Feedback
title: Popconfirm
description: Pop up a bubble confirmation box for an action.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*a7tqQ6wrdeAAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*iwYsQpeFcB0AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
A simple and compact dialog used for asking for user confirmation.
The difference with the `confirm` modal dialog is that it's more lightweight than the static popped full-screen confirm modal.
## Examples
### Basic
The basic example supports the title and description props of confirmation.
> `description` is supported in version `5.1.0`.
```tsx
import React from 'react';
import type { PopconfirmProps } from 'antd';
import { Button, message, Popconfirm } from 'antd';
const App: React.FC = () => {
const [messageApi, holder] = message.useMessage();
const confirm: PopconfirmProps['onConfirm'] = (e) => {
console.log(e);
messageApi.success('Click on Yes');
};
const cancel: PopconfirmProps['onCancel'] = (e) => {
console.log(e);
messageApi.error('Click on No');
};
return (
<>
{holder}
Delete
>
);
};
export default App;
```
### Locale text
Set `okText` and `cancelText` props to customize the button's labels.
```tsx
import React from 'react';
import { Button, Popconfirm } from 'antd';
const App: React.FC = () => (
Delete
);
export default App;
```
### Placement
There are 12 `placement` options available. Use `arrow: { pointAtCenter: true }` if you want the arrow to point at the center of target.
```tsx
import React from 'react';
import { Button, ConfigProvider, Flex, Popconfirm } from 'antd';
const text = 'Are you sure to delete this task?';
const description = 'Delete the task';
const buttonWidth = 80;
const App: React.FC = () => (
TL
Top
TR
LT
Left
LB
RT
Right
RB
BL
Bottom
BR
);
export default App;
```
### Auto Shift
Auto adjust Popup and arrow position when Popconfirm is close to the edge of the screen. Will be out of screen when exceed limitation.
```tsx
import React from 'react';
import { Button, Popconfirm } from 'antd';
const style: React.CSSProperties = {
width: '300vw',
height: '300vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
};
const App: React.FC = () => {
React.useEffect(() => {
document.documentElement.scrollTop = document.documentElement.clientHeight;
document.documentElement.scrollLeft = document.documentElement.clientWidth;
}, []);
return (
);
};
export default App;
```
### Conditional trigger
Make it pop up under some conditions.
```tsx
import React, { useState } from 'react';
import { Button, message, Popconfirm, Switch } from 'antd';
const App: React.FC = () => {
const [messageApi, contextHolder] = message.useMessage();
const [open, setOpen] = useState(false);
const [condition, setCondition] = useState(true);
const changeCondition = (checked: boolean) => {
setCondition(checked);
};
const confirm = () => {
setOpen(false);
messageApi.success('Next step.');
};
const cancel = () => {
setOpen(false);
messageApi.error('Click on cancel.');
};
const handleOpenChange = (newOpen: boolean) => {
if (!newOpen) {
setOpen(newOpen);
return;
}
// Determining condition before show the popconfirm.
console.log(condition);
if (condition) {
confirm(); // next step
} else {
setOpen(newOpen);
}
};
return (
<>
{contextHolder}
Delete a task
Whether directly execute:
>
);
};
export default App;
```
### Customize icon
Set `icon` props to customize the icon.
```tsx
import React from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Button, Popconfirm } from 'antd';
const App: React.FC = () => (
}
>
Delete
);
export default App;
```
### Asynchronously close
Asynchronously close a popconfirm when a the OK button is pressed. For example, you can use this pattern when you submit a form.
```tsx
import React, { useState } from 'react';
import { Button, Popconfirm } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [confirmLoading, setConfirmLoading] = useState(false);
const showPopconfirm = () => {
setOpen(true);
};
const handleOk = () => {
setConfirmLoading(true);
setTimeout(() => {
setOpen(false);
setConfirmLoading(false);
}, 2000);
};
const handleCancel = () => {
console.log('Clicked cancel button');
setOpen(false);
};
return (
Open Popconfirm with async logic
);
};
export default App;
```
### Asynchronously close on Promise
Asynchronously close a popconfirm when the OK button is pressed. For example, you can use this pattern when you submit a form.
```tsx
import React from 'react';
import { Button, Popconfirm } from 'antd';
const App: React.FC = () => {
const confirm = () =>
new Promise((resolve) => {
setTimeout(() => resolve(null), 3000);
});
return (
console.log('open change')}
>
Open Popconfirm with Promise
);
};
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Popconfirm by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Button, Flex, Popconfirm } from 'antd';
import type { GetProp, PopconfirmProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
container: css`
padding: 10px;
`,
}));
const styles: PopconfirmProps['styles'] = {
container: {
backgroundColor: '#eee',
boxShadow: 'inset 5px 5px 3px #fff, inset -5px -5px 3px #ddd, 0 0 3px rgba(0,0,0,0.2)',
},
title: {
color: '#262626',
},
content: {
color: '#262626',
},
};
const stylesFn: PopconfirmProps['styles'] = (
info,
): GetProp => {
if (!info.props.arrow) {
return {
container: {
backgroundColor: 'rgba(53, 71, 125, 0.8)',
padding: 12,
borderRadius: 4,
},
title: {
color: '#fff',
},
content: {
color: '#fff',
},
};
}
};
const App: React.FC = () => {
return (
Object Style
Function Style
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| cancelButtonProps | The cancel button props | [ButtonProps](/components/button/#api) | - | | × |
| cancelText | The text of the Cancel button | string | `Cancel` | | × |
| disabled | Whether show popconfirm when click its childrenNode | boolean | false | | × |
| icon | Customize icon of confirmation | ReactNode | <ExclamationCircleFilled /> | | × |
| okButtonProps | The ok button props | [ButtonProps](/components/button/#api) | - | | × |
| okText | The text of the Confirm button | string | `OK` | | × |
| okType | Button `type` of the Confirm button | string | `primary` | | × |
| showCancel | Show cancel button | boolean | true | 4.18.0 | × |
| title | The title of the confirmation box | ReactNode \| () => ReactNode | - | | × |
| description | The description of the confirmation box title | ReactNode \| () => ReactNode | - | 5.1.0 | × |
| onCancel | A callback of cancel | function(e) | - | | × |
| onConfirm | A callback of confirmation | function(e) | - | | × |
| onPopupClick | A callback of popup click | function(e) | - | 5.5.0 | × |
## Semantic DOM
https://ant.design/components/popconfirm/semantic.md
## Design Token
## Component Token (Popconfirm)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| zIndexPopup | z-index of Popconfirm | number | 1060 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextHeading | Control the font color of heading. | string | |
| colorWarning | Used to represent the warning map token, such as Notification, Alert, etc. Alert or Control component(like Input) will use these map tokens. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontWeightStrong | Control the font weight of heading components (such as h1, h2, h3) or selected item. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
## FAQ
For more questions, please refer to [Tooltip FAQ](/components/tooltip#faq).
---
## popover
Source: https://ant.design/components/popover.md
---
category: Components
group: Data Display
title: Popover
description: The floating card pops up when clicking/mouse hovering over an element.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*kfW5RrfF4L8AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*6b8fSKVVtXIAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
A simple popup menu to provide extra information or operations.
Comparing with `Tooltip`, besides information `Popover` card can also provide action elements like links and buttons.
## Examples
### Basic
The most basic example. The size of the floating layer depends on the contents region.
```tsx
import React from 'react';
import { Button, Popover } from 'antd';
const content = (
);
const App: React.FC = () => (
Hover me
);
export default App;
```
### Three ways to trigger
Mouse to click, focus and move in.
```tsx
import React from 'react';
import { Button, Popover, Space } from 'antd';
const content = (
);
const App: React.FC = () => (
Hover me
Focus me
Click me
);
export default App;
```
### Placement
There are 12 `placement` options available.
```tsx
import React from 'react';
import { Button, ConfigProvider, Flex, Popover } from 'antd';
const text = Title ;
const content = (
);
const buttonWidth = 80;
const App: React.FC = () => (
TL
Top
TR
LT
Left
LB
RT
Right
RB
BL
Bottom
BR
);
export default App;
```
### Arrow
Hide arrow by `arrow`.
```tsx
import React, { useMemo, useState } from 'react';
import { Button, ConfigProvider, Flex, Popover, Segmented } from 'antd';
import type { PopoverProps } from 'antd';
const text = Title ;
const buttonWidth = 80;
const content = (
);
const App: React.FC = () => {
const [arrow, setArrow] = useState<'Show' | 'Hide' | 'Center'>('Show');
const mergedArrow = useMemo(() => {
if (arrow === 'Hide') {
return false;
}
if (arrow === 'Show') {
return true;
}
return {
pointAtCenter: true,
};
}, [arrow]);
return (
TL
Top
TR
LT
Left
LB
RT
Right
RB
BL
Bottom
BR
);
};
export default App;
```
### Auto Shift
Auto adjust Popup and arrow position when Popover is close to the edge of the screen. Will be out of screen when exceed limitation.
```tsx
import React from 'react';
import { Button, Popover } from 'antd';
const style: React.CSSProperties = {
width: '300vw',
height: '300vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
};
const App: React.FC = () => {
React.useEffect(() => {
document.documentElement.scrollTop = document.documentElement.clientHeight;
document.documentElement.scrollLeft = document.documentElement.clientWidth;
}, []);
return (
);
};
export default App;
```
### Controlling the close of the dialog
Use `open` prop to control the display of the card.
```tsx
import React, { useState } from 'react';
import { Button, Popover } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const hide = () => {
setOpen(false);
};
const handleOpenChange = (newOpen: boolean) => {
setOpen(newOpen);
};
return (
Close}
title="Title"
trigger="click"
open={open}
onOpenChange={handleOpenChange}
>
Click me
);
};
export default App;
```
### Hover with click popover
The following example shows how to create a popover which can be hovered and clicked.
```tsx
import React, { useState } from 'react';
import { Button, Popover } from 'antd';
const hoverContent = This is hover content.
;
const clickContent = This is click content.
;
const App: React.FC = () => {
const [clicked, setClicked] = useState(false);
const [hovered, setHovered] = useState(false);
const hide = () => {
setClicked(false);
setHovered(false);
};
const handleHoverChange = (open: boolean) => {
setHovered(open);
setClicked(false);
};
const handleClickChange = (open: boolean) => {
setHovered(false);
setClicked(open);
};
return (
{clickContent}
Close
}
title="Click title"
trigger="click"
open={clicked}
onOpenChange={handleClickChange}
>
Hover and click
);
};
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Popover by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Button, Flex, Popover } from 'antd';
import type { GetProp, PopoverProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
container: css`
padding: 10px;
`,
}));
const styles: PopoverProps['styles'] = {
container: {
background: '#eee',
boxShadow: 'inset 5px 5px 3px #fff, inset -5px -5px 3px #ddd, 0 0 3px rgba(0,0,0,0.2)',
},
content: {
color: '#262626',
},
};
const stylesFn: PopoverProps['styles'] = (info): GetProp => {
if (!info.props.arrow) {
return {
container: {
backgroundColor: 'rgba(53, 71, 125, 0.8)',
padding: 12,
borderRadius: 4,
},
content: {
color: '#fff',
},
};
}
};
const App: React.FC = () => {
return (
Object Style
Function Style
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default value | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.23.0 |
| content | Content of the card | ReactNode \| () => ReactNode | - | | × |
| title | Title of the card | ReactNode \| () => ReactNode | - | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.23.0 |
## Note
Please ensure that the child node of `Popover` accepts `onMouseEnter`, `onMouseLeave`, `onFocus`, `onClick` events.
## Semantic DOM
https://ant.design/components/popover/semantic.md
## Design Token
## Component Token (Popover)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| titleMinWidth | Min width of Popover title | string \| number | 177 |
| zIndexPopup | z-index of Popover | number | 1030 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| borderRadiusXS | XS size border radius, used in some small border radius components, such as Segmented, Arrow and other components with small border radius. | number | |
| colorBgElevated | Container background color of the popup layer, in dark mode the color value of this token will be a little brighter than `colorBgContainer`. E.g: modal, pop-up, menu, etc. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextHeading | Control the font color of heading. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontWeightStrong | Control the font weight of heading components (such as h1, h2, h3) or selected item. | number | |
| lineHeight | Line height of text. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionEaseInOutCirc | Preset motion curve. | string | |
| motionEaseOutCirc | Preset motion curve. | string | |
| sizePopupArrow | The size of the component arrow | number | |
## FAQ
For more questions, please refer to [Tooltip FAQ](/components/tooltip#faq).
---
## progress
Source: https://ant.design/components/progress.md
---
category: Components
group: Feedback
title: Progress
description: Display the current progress of the operation.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*gK_4S6fDRfgAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*HJH8Tb1lcYAAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
If it will take a long time to complete an operation, you can use `Progress` to show the current progress and status.
- When an operation will interrupt the current interface, or it needs to run in the background for more than 2 seconds.
- When you need to display the completion percentage of an operation.
## Examples
### Progress bar
A standard progress bar.
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Circular progress bar
A circular progress bar.
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Mini size progress bar
Appropriate for a narrow area.
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Responsive circular progress bar
Responsive circular progress bar. When `width` is smaller than 20, progress information will be displayed in Tooltip.
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
`进行中,已完成${number}%`}
/>
代码发布
);
export default App;
```
### Mini size circular progress bar
A smaller circular progress bar.
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Dynamic
A dynamic progress bar is better.
```tsx
import React, { useState } from 'react';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Flex, Progress, Space } from 'antd';
const App: React.FC = () => {
const [percent, setPercent] = useState(0);
const increase = () => {
setPercent((prevPercent) => {
const newPercent = prevPercent + 10;
if (newPercent > 100) {
return 100;
}
return newPercent;
});
};
const decline = () => {
setPercent((prevPercent) => {
const newPercent = prevPercent - 10;
if (newPercent < 0) {
return 0;
}
return newPercent;
});
};
return (
} />
} />
);
};
export default App;
```
### Custom text format
You can set a custom text by setting the `format` prop.
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
`${percent} Days`} />
'Done'} />
);
export default App;
```
### Dashboard
By setting `type=dashboard`, you can get a dashboard style of progress easily.
```tsx
import React, { useState } from 'react';
import { Flex, Progress, Segmented } from 'antd';
import type { ProgressProps } from 'antd';
type GapPlacement = NonNullable;
const App: React.FC = () => {
const [gapPlacement, setGapPlacement] = useState('bottom');
const [gapDegree, setGapDegree] = useState(50);
return (
gapDegree:
{
setGapDegree(value);
}}
/>
gapPlacement:
{
setGapPlacement(value);
}}
/>
);
};
export default App;
```
### Progress bar with success segment
Show several parts of progress with different status.
```tsx
import React from 'react';
import { Flex, Progress, Tooltip } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Stroke Linecap
By setting `strokeLinecap="butt"`, you can change the linecaps from `round` to `butt`, see [stroke-linecap](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) for more information.
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Custom line gradient
Gradient encapsulation, `circle` and `dashboard` will ignore `strokeLinecap` when setting gradient.
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
import type { ProgressProps } from 'antd';
const twoColors: ProgressProps['strokeColor'] = {
'0%': '#108ee9',
'100%': '#87d068',
};
const conicColors: ProgressProps['strokeColor'] = {
'0%': '#87d068',
'50%': '#ffe58f',
'100%': '#ffccc7',
};
const App: React.FC = () => (
);
export default App;
```
### Progress bar with steps
A progress bar with steps.
```tsx
import React from 'react';
import { green, red } from '@ant-design/colors';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Circular progress bar with steps
A circular progress bar that support steps and color segments, default gap is 2px.
```tsx
import React from 'react';
import { Flex, Progress, Slider, Typography } from 'antd';
const App: React.FC = () => {
const [stepsCount, setStepsCount] = React.useState(5);
const [stepsGap, setStepsGap] = React.useState(7);
return (
<>
Custom count:
Custom gap:
>
);
};
export default App;
```
### Progress size
The size of progress.
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Change progress value position
Change the position of the progress value, you can use `percentPosition` to adjust it so that the progress bar value is inside, outside or at the bottom of the progress bar.
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Progress by passing objects or functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
import type { GetProp, ProgressProps } from 'antd';
const classNames: ProgressProps['classNames'] = {
root: 'demo-progress-root',
rail: 'demo-progress-rail',
track: 'demo-progress-track',
};
const stylesFn: ProgressProps['styles'] = (info): GetProp => {
const percent = info?.props?.percent ?? 0;
const hue = 200 - (200 * percent) / 100;
return {
track: {
backgroundImage: `
linear-gradient(
to right,
hsla(${hue}, 85%, 65%, 1),
hsla(${hue + 30}, 90%, 55%, 0.95)
)`,
borderRadius: 8,
transition: 'all 0.3s ease',
},
rail: {
backgroundColor: 'rgba(0, 0, 0, 0.1)',
borderRadius: 8,
},
};
};
const App: React.FC = () => (
);
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
Properties that shared by all types.
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | 6.0.0 | 6.0.0 |
| format | The template function of the content | function(percent, successPercent) | (percent) => percent + `%` | - | × |
| percent | To set the completion percentage | number | 0 | - | × |
| railColor | The color of unfilled part | string | - | - | × |
| showInfo | Whether to display the progress value and the status icon | boolean | true | - | × |
| status | To set the status of the Progress, options: `success` `exception` `normal` `active`(line only) | string | - | - | × |
| strokeColor | The color of progress bar | string | - | - | × |
| strokeLinecap | To set the style of the progress linecap | `round` \| `butt` \| `square`, see [stroke-linecap](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) | `round` | - | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | 6.0.0 | 6.0.0 |
| success | Configs of successfully progress bar | { percent: number, strokeColor: string } | - | - | × |
| ~~trailColor~~ | The color of unfilled part. Please use `railColor` instead | string | - | - | × |
| type | To set the type, options: `line` `circle` `dashboard` | string | `line` | - | × |
| size | Progress size | number \| \[number \| string, number] \| { width: number, height: number } \| "small" \| "medium" | "medium" | 5.3.0, Object: 5.18.0 | × |
### `type="line"`
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| steps | The total step count | number | - | - |
| rounding | The function to round the value | (step: number) => number | Math.round | 5.24.0 |
| strokeColor | The color of progress bar, render `linear-gradient` when passing an object, could accept `string[]` when has `steps`. | string \| string[] \| { from: string; to: string; direction: string } | - | 4.21.0: `string[]` |
| percentPosition | Progress value position, passed in object, `align` indicates the horizontal position of the value, `type` indicates whether the value is inside or outside the progress bar | { align: string; type: string } | { align: \"end\", type: \"outer\" } | 5.18.0 |
### `type="circle"`
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| steps | The total step count. When passing an object, `count` refers to the number of steps, and `gap` refers to the distance between them. When passing a number, the default value for `gap` is 2. | number \| { count: number, gap: number } | - | 5.16.0 |
| strokeColor | The color of circular progress, render gradient when passing an object | string \| { number%: string } | - | - |
| strokeWidth | To set the width of the circular progress, unit: percentage of the canvas width | number | 6 | - |
### `type="dashboard"`
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| steps | The total step count. When passing an object, `count` refers to the number of steps, and `gap` refers to the distance between them. When passing a number, the default value for `gap` is 2. | number \| { count: number, gap: number } | - | 5.16.0 |
| gapDegree | The gap degree of half circle, 0 ~ 295 | number | 75 | - |
| gapPlacement | The gap placement, options: `top` `bottom` `start` `end` | string | `bottom` | - |
| ~~gapPosition~~ | The gap position, options: `top` `bottom` `left` `right`, please use `gapPlacement` instead | string | `bottom` | - |
| strokeWidth | To set the width of the dashboard progress, unit: percentage of the canvas width | number | 6 | - |
## Semantic DOM
https://ant.design/components/progress/semantic.md
## Design Token
## Component Token (Progress)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| circleIconFontSize | Icon size of circular progress bar | string | 1.1666666666666667em |
| circleTextColor | Text color of circular progress bar | string | rgba(0,0,0,0.88) |
| circleTextFontSize | Text size of circular progress bar | string | 1em |
| defaultColor | Default color of progress bar | string | #1677ff |
| lineBorderRadius | Border radius of line progress bar | number | 100 |
| remainingColor | Color of remaining part of progress bar | string | rgba(0,0,0,0.06) |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorBgContainer | Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. | string | |
| colorError | Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. | string | |
| colorSuccess | Used to represent the token sequence of operation success, such as Result, Progress and other components will use these map tokens. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorWhite | Pure white color don't changed by theme | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeSM | Small font size | number | |
| lineHeight | Line height of text. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseInOutCirc | Preset motion curve. | string | |
| motionEaseOutQuint | Preset motion curve. | string | |
| paddingXXS | Control the extra extra small padding of the element. | number | |
---
## qr-code
Source: https://ant.design/components/qr-code.md
---
category: Components
title: QRCode
description: Components that can convert text into QR codes, and support custom color and logo.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*cJopQrf0ncwAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*M4PBTZ_n9OgAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group:
title: Data Display
order: 5
---
## When To Use
Used when the text needs to be converted into a QR Code.
## Examples
### base
Basic Usage.
```tsx
import React from 'react';
import { Input, QRCode, Space } from 'antd';
const App: React.FC = () => {
const [text, setText] = React.useState('https://ant.design/');
return (
setText(e.target.value)}
/>
);
};
export default App;
```
### With Icon
QRCode with Icon.
```tsx
import React from 'react';
import { QRCode } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### other status
The status can be controlled by the value `status`, four values of `active`, `expired`, `loading`, `scanned` are provided.
```tsx
import React from 'react';
import { Flex, QRCode } from 'antd';
const value = 'https://ant.design';
const App: React.FC = () => (
console.log('refresh')} />
);
export default App;
```
### custom status render
You can control the rendering logic of the QR code in different states through the value of `statusRender`.
```tsx
import React from 'react';
import { CheckCircleFilled, CloseCircleFilled, ReloadOutlined } from '@ant-design/icons';
import type { QRCodeProps } from 'antd';
import { Button, Flex, QRCode, Space, Spin } from 'antd';
const value = 'https://ant.design';
const customStatusRender: QRCodeProps['statusRender'] = (info) => {
switch (info.status) {
case 'expired':
return (
{info.locale?.expired}
{info.locale?.refresh}
);
case 'loading':
return (
Loading...
);
case 'scanned':
return (
{info.locale?.scanned}
);
default:
return null;
}
};
const App: React.FC = () => (
console.log('refresh')}
statusRender={customStatusRender}
/>
);
export default App;
```
### Custom Render Type
Customize the rendering results by `type`, provide options `canvas` and `svg`.
```tsx
import React from 'react';
import { QRCode, Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Custom Size
Custom Size.
```tsx
import React, { useState } from 'react';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, QRCode, Space } from 'antd';
const MIN_SIZE = 48;
const MAX_SIZE = 300;
const App: React.FC = () => {
const [size, setSize] = useState(160);
const increase = () => {
setSize((prevSize) => {
const newSize = prevSize + 10;
if (newSize >= MAX_SIZE) {
return MAX_SIZE;
}
return newSize;
});
};
const decline = () => {
setSize((prevSize) => {
const newSize = prevSize - 10;
if (newSize <= MIN_SIZE) {
return MIN_SIZE;
}
return newSize;
});
};
return (
<>
}>
Smaller
= MAX_SIZE} icon={ }>
Larger
>
);
};
export default App;
```
### Custom Color
Custom Color.
```tsx
import React from 'react';
import { QRCode, Space, theme } from 'antd';
const { useToken } = theme;
const App: React.FC = () => {
const { token } = useToken();
return (
);
};
export default App;
```
### Download QRCode
A way to download QRCode.
```tsx
import React from 'react';
import { Button, QRCode, Segmented, Space } from 'antd';
import type { QRCodeProps } from 'antd';
function doDownload(url: string, fileName: string) {
const a = document.createElement('a');
a.download = fileName;
a.href = url;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
const downloadCanvasQRCode = () => {
const canvas = document.getElementById('myqrcode')?.querySelector('canvas');
if (canvas) {
const url = canvas.toDataURL();
doDownload(url, 'QRCode.png');
}
};
const downloadSvgQRCode = () => {
const svg = document.getElementById('myqrcode')?.querySelector('svg');
const svgData = new XMLSerializer().serializeToString(svg!);
const blob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(blob);
doDownload(url, 'QRCode.svg');
};
const App: React.FC = () => {
const [renderType, setRenderType] = React.useState('canvas');
return (
Download
);
};
export default App;
```
### Error Level
set Error Level.
```tsx
import React, { useState } from 'react';
import type { QRCodeProps } from 'antd';
import { QRCode, Segmented } from 'antd';
const App: React.FC = () => {
const [level, setLevel] = useState('L');
return (
<>
>
);
};
export default App;
```
### Advanced Usage
With Popover.
```tsx
import React from 'react';
import { Button, Popover, QRCode } from 'antd';
const App: React.FC = () => (
}>
Hover me
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of QRCode by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Flex, QRCode } from 'antd';
import type { GetProp, QRCodeProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
border: 1px solid #ccc;
border-radius: 8px;
padding: 16px;
`,
}));
const stylesObject: QRCodeProps['styles'] = {
root: {
border: '2px solid #1890ff',
borderRadius: 8,
padding: 16,
backgroundColor: 'rgb(24, 144, 255, 0.1)',
},
};
const stylesFunction: QRCodeProps['styles'] = (info): GetProp => {
if (info.props.type === 'canvas') {
return {
root: {
border: '2px solid #ff4d4f',
borderRadius: 8,
padding: 16,
backgroundColor: 'rgba(255, 77, 79, 0.1)',
},
};
}
};
const App: React.FC = () => {
const sharedProps: QRCodeProps = {
value: 'https://ant.design/',
size: 160,
classNames,
};
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
> This component is available since `antd@5.1.0`
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| :-- | :-- | :-- | :-- | :-- | --- |
| value | scanned text | `string \| string[]` | - | `string[]`: 5.28.0 | × |
| type | render type | `canvas \| svg` | `canvas` | 5.6.0 | × |
| icon | include image url (only image link are supported) | string | - | - | × |
| size | QRCode size | number | 160 | - | × |
| iconSize | include image size | number \| { width: number; height: number } | 40 | 5.19.0 | × |
| color | QRCode Color | string | `#000` | - | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | 6.0.0 | 6.0.0 |
| bgColor | QRCode Background Color | string | `transparent` | 5.5.0 | × |
| marginSize | Quiet zone size (in modules). `0` means no margin | number | `0` | 6.2.0 | × |
| bordered | Whether has border style | boolean | true | - | × |
| errorLevel | Error Code Level | `'L' \| 'M' \| 'Q' \| 'H'` | `M` | - | × |
| boostLevel | If enabled, the Error Correction Level of the result may be higher than the specified Error Correction Level | `boolean` | true | 5.28.0 | × |
| status | QRCode status | `active \| expired \| loading \| scanned` | `active` | scanned: 5.13.0 | × |
| statusRender | custom status render | (info: [StatusRenderInfo](/components/qr-code#statusrenderinfo)) => React.ReactNode | - | 5.20.0 | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | 6.0.0 | 6.0.0 |
### StatusRenderInfo
```typescript
type StatusRenderInfo = {
status: QRStatus;
locale: Locale['QRCode'];
onRefresh?: () => void;
};
```
## Semantic DOM
https://ant.design/components/qr-code/semantic.md
## Design Token
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| colorSplit | Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorWhite | Pure white color don't changed by theme | string | |
| controlHeight | The height of the basic controls such as buttons and input boxes in Ant Design | number | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| lineHeight | Line height of text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| paddingSM | Control the small padding of the element. | number | |
## FAQ
### About QRCode ErrorLevel {#faq-error-correction-level}
The ErrorLevel means that the QR code can be scanned normally after being blocked, and the maximum area that can be blocked is the error correction rate.
Generally, the QR code is divided into 4 error correction levels: Level `L` can correct about `7%` errors, Level `M` can correct about `15%` errors, Level `Q` can correct about `25%` errors, and Level `H` can correct about `30%` errors. When the content encoding of the QR code carries less information, in other words, when the value link is short, set different error correction levels, and the generated image will not change.
> For more information, see the: [https://www.qrcode.com/en/about/error_correction](https://www.qrcode.com/en/about/error_correction.html)
### ⚠️⚠️⚠️ Cannot scan the QR code? {#faq-cannot-scan}
If the QR code cannot be scanned for identification, it may be because the link address is too long, which leads to too dense pixels.
You can configure the QR code to be larger through size, or shorten the link through short link services.
---
## radio
Source: https://ant.design/components/radio.md
---
category: Components
group: Data Entry
title: Radio
description: Used to select a single state from multiple options.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*mrPVRope68wAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*xPfTSphsiA0AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
- Used to select a single state from multiple options.
- The difference from Select is that Radio is visible to the user and can facilitate the comparison of choice, which means there shouldn't be too many of them.
```tsx
// When use Radio.Group, recommended ✅
return (
);
// Not recommended 🙅🏼♀️
return (
A
B
C
);
```
## Examples
### Basic
The simplest use.
```tsx
import React from 'react';
import { Radio } from 'antd';
const App: React.FC = () => Radio ;
export default App;
```
### disabled
Radio unavailable.
```tsx
import React, { useState } from 'react';
import { Button, Radio } from 'antd';
const App: React.FC = () => {
const [disabled, setDisabled] = useState(true);
const toggleDisabled = () => {
setDisabled(!disabled);
};
return (
<>
Disabled
Disabled
Toggle disabled
>
);
};
export default App;
```
### Radio Group
A group of radio components.
```tsx
import React, { useState } from 'react';
import {
BarChartOutlined,
DotChartOutlined,
LineChartOutlined,
PieChartOutlined,
} from '@ant-design/icons';
import type { RadioChangeEvent } from 'antd';
import { Flex, Radio } from 'antd';
const App: React.FC = () => {
const [value, setValue] = useState(1);
const onChange = (e: RadioChangeEvent) => {
setValue(e.target.value);
};
return (
LineChart
),
},
{
value: 2,
className: 'option-2',
label: (
DotChart
),
},
{
value: 3,
className: 'option-3',
label: (
BarChart
),
},
{
value: 4,
className: 'option-4',
label: (
PieChart
),
},
]}
/>
);
};
export default App;
```
### Vertical Radio.Group
Vertical Radio.Group, with more radios.
```tsx
import React, { useState } from 'react';
import type { RadioChangeEvent, RadioGroupProps } from 'antd';
import { Flex, Input, Radio } from 'antd';
const labelStyle: React.CSSProperties = {
height: 32,
lineHeight: '32px',
};
const buttonOptions: RadioGroupProps['options'] = [
{ label: 'Apple', value: 'Apple', className: 'label-1' },
{ label: 'Pear', value: 'Pear', className: 'label-2' },
{ label: 'Orange', value: 'Orange', title: 'Orange', className: 'label-3' },
];
const App: React.FC = () => {
const [value, setValue] = useState(1);
const onChange = (e: RadioChangeEvent) => {
setValue(e.target.value);
};
return (
More...
{value === 4 && (
)}
>
),
},
]}
/>
);
};
export default App;
```
### Block Radio.Group
The `block` property will make a Radio.Group fit to its parent width.
```tsx
import React from 'react';
import { Flex, Radio } from 'antd';
import type { CheckboxGroupProps } from 'antd/es/checkbox';
const options: CheckboxGroupProps['options'] = [
{ label: 'Apple', value: 'Apple' },
{ label: 'Pear', value: 'Pear' },
{ label: 'Orange', value: 'Orange' },
];
const App: React.FC = () => (
);
export default App;
```
### Radio.Group group - optional
Render radios by configuring `options`. Radio type can also be set through the `optionType` parameter.
```tsx
import React, { useState } from 'react';
import type { RadioChangeEvent } from 'antd';
import { Radio } from 'antd';
import type { CheckboxGroupProps } from 'antd/es/checkbox';
const plainOptions: CheckboxGroupProps['options'] = ['Apple', 'Pear', 'Orange'];
const options: CheckboxGroupProps['options'] = [
{ label: 'Apple', value: 'Apple', className: 'label-1' },
{ label: 'Pear', value: 'Pear', className: 'label-2' },
{ label: 'Orange', value: 'Orange', title: 'Orange', className: 'label-3' },
];
const optionsWithDisabled: CheckboxGroupProps['options'] = [
{ label: 'Apple', value: 'Apple', className: 'label-1' },
{ label: 'Pear', value: 'Pear', className: 'label-2' },
{ label: 'Orange', value: 'Orange', className: 'label-3', disabled: true },
];
const App: React.FC = () => {
const [value1, setValue1] = useState('Apple');
const [value2, setValue2] = useState('Apple');
const [value3, setValue3] = useState('Apple');
const [value4, setValue4] = useState('Apple');
const onChange1 = ({ target: { value } }: RadioChangeEvent) => {
console.log('radio1 checked', value);
setValue1(value);
};
const onChange2 = ({ target: { value } }: RadioChangeEvent) => {
console.log('radio2 checked', value);
setValue2(value);
};
const onChange3 = ({ target: { value } }: RadioChangeEvent) => {
console.log('radio3 checked', value);
setValue3(value);
};
const onChange4 = ({ target: { value } }: RadioChangeEvent) => {
console.log('radio4 checked', value);
setValue4(value);
};
return (
<>
>
);
};
export default App;
```
### radio style
The combination of radio button style.
```tsx
import React from 'react';
import type { RadioChangeEvent } from 'antd';
import { Flex, Radio } from 'antd';
const onChange = (e: RadioChangeEvent) => {
console.log(`radio checked:${e.target.value}`);
};
const App: React.FC = () => (
Hangzhou
Shanghai
Beijing
Chengdu
Hangzhou
Shanghai
Beijing
Chengdu
Hangzhou
Shanghai
Beijing
Chengdu
);
export default App;
```
### Radio.Group with name
Passing the `name` property to all `input[type="radio"]` that are in the same Radio.Group. It is usually used to let the browser see your Radio.Group as a real "group" and keep the default behavior. For example, using left/right keyboard arrow to change your selection that in the same Radio.Group.
```tsx
import React from 'react';
import { Radio } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Size
There are three sizes available: large, medium, and small. It can coordinate with input box.
```tsx
import React from 'react';
import { Flex, Radio } from 'antd';
const App: React.FC = () => (
Hangzhou
Shanghai
Beijing
Chengdu
Hangzhou
Shanghai
Beijing
Chengdu
Hangzhou
Shanghai
Beijing
Chengdu
);
export default App;
```
### Solid radio button
Solid radio button style.
```tsx
import React from 'react';
import { Flex, Radio } from 'antd';
const App: React.FC = () => (
Hangzhou
Shanghai
Beijing
Chengdu
Hangzhou
Shanghai
Beijing
Chengdu
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of radio by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Flex, Radio } from 'antd';
import type { GetProp, RadioProps } from 'antd';
import { createStyles } from 'antd-style';
import clsx from 'clsx';
const useStyles = createStyles(({ token, css }) => ({
root: css`
border-radius: ${token.borderRadius}px;
background-color: ${token.colorBgContainer};
`,
icon: css`
border-color: ${token.colorWarning};
`,
label: css`
color: ${token.colorTextDisabled};
font-weight: bold;
`,
iconChecked: css`
background-color: ${token.colorWarning};
`,
labelChecked: css`
color: ${token.colorWarning};
`,
}));
// Object style
const styles: RadioProps['styles'] = {
icon: {
borderRadius: 6,
},
label: {
color: 'blue',
},
};
const App: React.FC = () => {
const [value, setValue] = React.useState<'styles' | 'classNames'>('styles');
const { styles: classNamesStyles } = useStyles();
// Function classNames - dynamically adjust based on checked state
const classNamesFn: RadioProps['classNames'] = (
info,
): GetProp => {
if (info.props.checked) {
return {
root: clsx(classNamesStyles.root),
icon: clsx(classNamesStyles.icon, classNamesStyles.iconChecked),
label: clsx(classNamesStyles.label, classNamesStyles.labelChecked),
};
}
return {
root: classNamesStyles.root,
icon: classNamesStyles.icon,
label: classNamesStyles.label,
};
};
return (
setValue('styles')}
>
Object styles
setValue('classNames')}
>
Function classNames
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Radio/Radio.Button
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| checked | Specifies whether the radio is selected | boolean | false | | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | 6.0.0 | 6.0.0 |
| defaultChecked | Specifies the initial state: whether or not the radio is selected | boolean | false | | × |
| disabled | Disable radio | boolean | false | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | 6.0.0 | 6.0.0 |
| value | According to value for comparison, to determine whether the selected | any | - | | × |
### Radio.Group
Radio group can wrap a group of `Radio`.
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| block | Option to fit RadioGroup width to its parent width | boolean | false | 5.21.0 |
| buttonStyle | The style type of radio button | `outline` \| `solid` | `outline` | |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | 6.0.0 |
| defaultValue | Default selected value | any | - | |
| disabled | Disable all radio buttons | boolean | false | |
| name | The `name` property of all `input[type="radio"]` children. If not set, it will fallback to a randomly generated name | string | - | |
| options | Set children optional | string\[] \| number\[] \| Array<[CheckboxOptionType](#checkboxoptiontype)> | - | |
| optionType | Set Radio optionType | `default` \| `button` | `default` | 4.4.0 |
| orientation | Orientation | `horizontal` \| `vertical` | `horizontal` | |
| size | The size of radio button style | `large` \| `medium` \| `small` | - | |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | 6.0.0 |
| value | Used for setting the currently selected value | any | - | |
| vertical | If true, the Radio group will be vertical. Simultaneously existing with `orientation`, `orientation` takes priority | boolean | false | |
| onChange | The callback function that is triggered when the state changes | function(e:Event) | - | |
### CheckboxOptionType
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| label | The text used to display as the Radio option | `string` | - | 4.4.0 |
| value | The value associated with the Radio option | `string` \| `number` \| `boolean` | - | 4.4.0 |
| style | The style to apply to the Radio option | `React.CSSProperties` | - | 4.4.0 |
| className | className of the Radio option | `string` | - | 5.25.0 |
| disabled | Specifies whether the Radio option is disabled | `boolean` | `false` | 4.4.0 |
| title | Adds the Title attribute value | `string` | - | 4.4.0 |
| id | Adds the Radio Id attribute value | `string` | - | 4.4.0 |
| onChange | Triggered when the value of the Radio Group changes | `(e: CheckboxChangeEvent) => void;` | - | 4.4.0 |
| required | Specifies whether the Radio option is required | `boolean` | `false` | 4.4.0 |
## Methods
### Radio
| Name | Description |
| ------- | ------------ |
| blur() | Remove focus |
| focus() | Get focus |
## Semantic DOM
https://ant.design/components/radio/semantic.md
## Design Token
## Component Token (Radio)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| buttonBg | Background color of Radio button | string | #ffffff |
| buttonCheckedBg | Background color of checked Radio button | string | #ffffff |
| buttonCheckedBgDisabled | Background color of checked and disabled Radio button | string | rgba(0,0,0,0.15) |
| buttonCheckedColorDisabled | Color of checked and disabled Radio button text | string | rgba(0,0,0,0.25) |
| buttonColor | Color of Radio button text | string | rgba(0,0,0,0.88) |
| buttonPaddingInline | Horizontal padding of Radio button | number | 15 |
| buttonSolidCheckedActiveBg | Background color of checked solid Radio button text when active | string | #0958d9 |
| buttonSolidCheckedBg | Background color of checked solid Radio button text | string | #1677ff |
| buttonSolidCheckedColor | Color of checked solid Radio button text | string | #fff |
| buttonSolidCheckedHoverBg | Background color of checked solid Radio button text when hover | string | #4096ff |
| dotColorDisabled | Color of disabled Radio dot | string | rgba(0,0,0,0.25) |
| dotSize | Size of Radio dot | number | 8 |
| radioSize | Radio size | number | 16 |
| wrapperMarginInlineEnd | Margin right of Radio button | number | 8 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadius | Border radius of base components | number | |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| colorBgContainer | Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. | string | |
| colorBgContainerDisabled | Control the background color of container in disabled state. | string | |
| colorBorder | Default border color, used to separate different elements, such as: form separator, card separator, etc. | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorPrimaryActive | Dark active state under the main color gradient. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorPrimaryHover | Hover state under the main color gradient. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDisabled | Control the color of text in disabled state. | string | |
| controlHeight | The height of the basic controls such as buttons and input boxes in Ant Design | number | |
| controlHeightLG | LG component height | number | |
| controlHeightSM | SM component height | number | |
| controlOutline | Control the outline color of input component. | string | |
| controlOutlineWidth | Control the outline width of input component. | number | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeLG | Large font size | number | |
| lineHeight | Line height of text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseInOutCirc | Preset motion curve. | string | |
| paddingXS | Control the extra small padding of the element. | number | |
---
## rate
Source: https://ant.design/components/rate.md
---
category: Components
group: Data Entry
title: Rate
description: Used for rating operation on something.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*oyOcTrB12_YAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*M7_ER7GJr6wAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
- Show evaluation.
- A quick rating operation on something.
## Examples
### Basic
The simplest usage.
```tsx
import React from 'react';
import { Rate } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Sizes
Three sizes.
```tsx
import React from 'react';
import { Flex, Rate } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Half star
Support select half star.
```tsx
import React from 'react';
import { Rate } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Show copywriting
Add copywriting in rate components.
```tsx
import React, { useState } from 'react';
import { Flex, Rate } from 'antd';
import type { RateProps } from 'antd';
const desc: RateProps['tooltips'] = [
'terrible',
{ placement: 'top', title: 'bad', trigger: 'hover' },
'normal',
'good',
'wonderful',
];
function getDescTitle(value: number, desc: RateProps['tooltips']) {
const item = desc?.[value - 1];
return item && typeof item === 'object' ? item.title : item;
}
const App: React.FC = () => {
const [value, setValue] = useState(3);
return (
{value ? {getDescTitle(value, desc) as React.ReactNode} : null}
);
};
export default App;
```
### Read only
Read only, can't use mouse to interact.
```tsx
import React from 'react';
import { Rate } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Clear star
Allow clearing the rating when clicking the same star again.
```tsx
import React from 'react';
import { Flex, Rate } from 'antd';
const App: React.FC = () => (
allowClear: true
allowClear: false
);
export default App;
```
### Other Character
Replace the default star to other character like alphabet, digit, iconfont or even Chinese word.
```tsx
import React from 'react';
import { HeartOutlined } from '@ant-design/icons';
import { Flex, Rate } from 'antd';
const App: React.FC = () => (
} allowHalf />
);
export default App;
```
### Customize character
Can customize each character using `(RateProps) => ReactNode`.
```tsx
import React from 'react';
import { FrownOutlined, MehOutlined, SmileOutlined } from '@ant-design/icons';
import { Flex, Rate } from 'antd';
const customIcons: Record = {
1: ,
2: ,
3: ,
4: ,
5: ,
};
const App: React.FC = () => (
index + 1} />
customIcons[index + 1]} />
);
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| allowClear | Whether to allow clear when click again | boolean | true | | × |
| allowHalf | Whether to allow semi selection | boolean | false | | × |
| character | The custom character of rate | ReactNode \| (RateProps) => ReactNode | <StarFilled /> | function(): 4.4.0 | × |
| count | Star count | number | 5 | | × |
| defaultValue | The default value | number | 0 | | × |
| disabled | If read only, unable to interact | boolean | false | | × |
| keyboard | Support keyboard operation | boolean | true | 5.18.0 | × |
| size | Star size | 'small' \| 'medium' \| 'large' | 'medium' | | × |
| tooltips | Customize tooltip by each character | [TooltipProps](/components/tooltip#api)[] \| string\[] | - | | × |
| value | The current value | number | - | | × |
| onBlur | Callback when component lose focus | function() | - | | × |
| onChange | Callback when select value | function(value: number) | - | | × |
| onFocus | Callback when component get focus | function() | - | | × |
| onHoverChange | Callback when hover item | function(value: number) | - | | × |
| onKeyDown | Callback when keydown on component | function(event) | - | | × |
## Methods
| Name | Description |
| ------- | ------------ |
| blur() | Remove focus |
| focus() | Get focus |
## Design Token
## Component Token (Rate)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| starBg | Star background color | string | rgba(0,0,0,0.06) |
| starColor | Star color | string | #fadb14 |
| starHoverScale | Scale of star when hover | readonly string[] \| Transform \| readonly Transform[] \| { _multi_value_?: boolean; _skip_check_?: boolean; value: readonly string[] \| Transform \| (readonly string[] \| Transform \| undefined)[] \| undefined } \| undefined | scale(1.1) |
| starSize | Star size | number | 20 |
| starSizeLG | Large star size | number | 25 |
| starSizeSM | Small star size | number | 15 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| lineHeight | Line height of text. | number | |
| lineWidth | Border width of base components | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
---
## result
Source: https://ant.design/components/result.md
---
group: Feedback
category: Components
title: Result
description: Used to feedback the processing results of a series of operations.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*-e2IRroDJyEAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*-0kxQrbHx2kAAAAAAAAAAAAADrJ8AQ/original
---
## When To Use
Use when important operations need to inform the user to process the results and the feedback is more complicated.
## Examples
### Success
Show successful results.
```tsx
import React from 'react';
import { Button, Result } from 'antd';
const App: React.FC = () => (
Go Console
,
Buy Again ,
]}
/>
);
export default App;
```
### Info
Show processing results.
```tsx
import React from 'react';
import { Button, Result } from 'antd';
const App: React.FC = () => (
Go Console
}
/>
);
export default App;
```
### Warning
The result of the warning.
```tsx
import React from 'react';
import { Button, Result } from 'antd';
const App: React.FC = () => (
Go Console
}
/>
);
export default App;
```
### 403
you are not authorized to access this page.
```tsx
import React from 'react';
import { Button, Result } from 'antd';
const App: React.FC = () => (
Back Home}
/>
);
export default App;
```
### 404
The page you visited does not exist.
```tsx
import React from 'react';
import { Button, Result } from 'antd';
const App: React.FC = () => (
Back Home}
/>
);
export default App;
```
### 500
Something went wrong on server.
```tsx
import React from 'react';
import { Button, Result } from 'antd';
const App: React.FC = () => (
Back Home}
/>
);
export default App;
```
### Error
Complex error feedback.
```css
.site-result-demo-error-icon {
color: red;
}
```
```tsx
import React from 'react';
import { CloseCircleOutlined } from '@ant-design/icons';
import { Button, Result, Typography } from 'antd';
const { Paragraph, Text } = Typography;
const App: React.FC = () => (
Go Console
,
Buy Again ,
]}
>
);
export default App;
```
### Custom icon
Custom icon.
```tsx
import React from 'react';
import { SmileOutlined } from '@ant-design/icons';
import { Button, Result } from 'antd';
const App: React.FC = () => (
}
title="Great, we have done all the operations!"
extra={Next }
/>
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Result by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Button, Result } from 'antd';
import type { GetProp, ResultProps } from 'antd';
const classNamesObject: ResultProps['classNames'] = {
root: 'demo-result-root',
title: 'demo-result-title',
subTitle: 'demo-result-subtitle',
icon: 'demo-result-icon',
extra: 'demo-result-extra',
body: 'demo-result-body',
};
const classNamesFn: ResultProps['classNames'] = (
info,
): GetProp => {
if (info.props.status === 'success') {
return {
root: 'demo-result-root--success',
};
}
return {
root: 'demo-result-root--default',
};
};
const stylesObject: ResultProps['styles'] = {
root: { borderWidth: 2, borderStyle: 'dashed', padding: 16 },
title: { fontStyle: 'italic', color: '#1890ff' },
subTitle: { fontWeight: 'bold' },
icon: { opacity: 0.8 },
extra: { backgroundColor: '#f0f0f0', padding: 8 },
body: { backgroundColor: '#fafafa', padding: 12 },
};
const stylesFn: ResultProps['styles'] = (info): GetProp => {
if (info.props.status === 'error') {
return {
root: { backgroundColor: '#fff2f0', borderColor: '#ff4d4f' },
title: { color: '#ff4d4f' },
};
} else {
return {
root: { backgroundColor: '#f6ffed', borderColor: '#52c41a' },
title: { color: '#52c41a' },
};
}
};
const App: React.FC = () => {
return (
<>
Action}
>
Content area
Action}
/>
>
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | Customize class for each semantic structure inside the component. Supports object or function | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | 6.0.0 | 6.0.0 |
| extra | Operating area | ReactNode | - | | × |
| icon | Custom back icon | ReactNode | - | | × |
| status | Result status, decide icons and colors | `success` \| `error` \| `info` \| `warning` \| `404` \| `403` \| `500` | `info` | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | 6.0.0 | 6.0.0 |
| subTitle | The subTitle | ReactNode | - | | × |
| title | The title | ReactNode | - | | × |
## Semantic DOM
https://ant.design/components/result/semantic.md
## Design Token
## Component Token (Result)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| extraMargin | Margin of extra area | Margin \| undefined | 24px 0 0 0 |
| iconFontSize | Icon size | string \| number | 72 |
| subtitleFontSize | Subtitle font size | number | 14 |
| titleFontSize | Title font size | string \| number | 24 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorError | Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. | string | |
| colorFillAlter | Control the alternative background color of element. | string | |
| colorInfo | Used to represent the operation information of the Token sequence, such as Alert, Tag, Progress, and other components use these map tokens. | string | |
| colorSuccess | Used to represent the token sequence of operation success, such as Result, Progress and other components will use these map tokens. | string | |
| colorTextDescription | Control the font color of text description. | string | |
| colorTextHeading | Control the font color of heading. | string | |
| colorWarning | Used to represent the warning map token, such as Notification, Alert, etc. Alert or Control component(like Input) will use these map tokens. | string | |
| lineHeight | Line height of text. | number | |
| lineHeightHeading3 | Line height of h3 tag. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| padding | Control the padding of the element. | number | |
| paddingLG | Control the large padding of the element. | number | |
| paddingXL | Control the extra large padding of the element. | number | |
| paddingXS | Control the extra small padding of the element. | number | |
---
## segmented
Source: https://ant.design/components/segmented.md
---
category: Components
group: Data Display
title: Segmented
description: Display multiple options and allow users to select a single option.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*XJR2TbS1aaQAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*-9tSSoO_MkIAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
This component is available since `antd@4.20.0`.
## When To Use
- When displaying multiple options and user can select a single option;
- When switching the selected option, the content of the associated area changes.
## Examples
### Basic
The most basic usage.
```tsx
import React from 'react';
import { Segmented } from 'antd';
const Demo: React.FC = () => (
options={['Daily', 'Weekly', 'Monthly', 'Quarterly', 'Yearly']}
onChange={(value) => {
console.log(value); // string
}}
/>
);
export default Demo;
```
### Vertical Direction
Make it vertical.
```tsx
import React from 'react';
import { AppstoreOutlined, BarsOutlined } from '@ant-design/icons';
import { Segmented } from 'antd';
const Demo: React.FC = () => (
},
{ value: 'Kanban', icon: },
]}
/>
);
export default Demo;
```
### Block Segmented
`block` property will make the `Segmented` fit to its parent width.
```tsx
import React from 'react';
import { Segmented } from 'antd';
const Demo: React.FC = () => (
options={[123, 456, 'longtext-longtext-longtext-longtext']} block />
);
export default Demo;
```
### Round shape
Round shape of Segmented.
```tsx
import React, { useState } from 'react';
import { MoonOutlined, SunOutlined } from '@ant-design/icons';
import { Flex, Segmented } from 'antd';
import type { SegmentedProps } from 'antd';
type SizeType = NonNullable;
const Demo: React.FC = () => {
const [size, setSize] = useState('medium');
return (
options={['small', 'medium', 'large']} value={size} onChange={setSize} />
},
{ value: 'dark', icon: },
]}
/>
);
};
export default Demo;
```
### Disabled
Disabled Segmented.
```tsx
import React from 'react';
import { Flex, Segmented } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Controlled mode
Controlled Segmented.
```tsx
import React, { useState } from 'react';
import { Segmented } from 'antd';
const Demo: React.FC = () => {
const [value, setValue] = useState('Map');
return (
options={['Map', 'Transit', 'Satellite']}
value={value}
onChange={setValue}
/>
);
};
export default Demo;
```
### Custom Render
Custom each Segmented Item.
```tsx
import React from 'react';
import { UserOutlined } from '@ant-design/icons';
import { Avatar, Flex, Segmented } from 'antd';
const App: React.FC = () => (
User 1
),
value: 'user1',
tooltip: { title: 'hello user1', color: 'gold' },
},
{
label: (
),
value: 'user2',
tooltip: { title: 'hello user2', color: 'pink' },
},
{
label: (
),
value: 'user3',
tooltip: { title: 'hello user3', color: 'geekblue' },
},
]}
/>
Spring
Jan-Mar
),
value: 'spring',
},
{
label: (
),
value: 'summer',
},
{
label: (
),
value: 'autumn',
},
{
label: (
),
value: 'winter',
},
]}
/>
);
export default App;
```
### Dynamic
Load `options` dynamically.
```tsx
import React, { useState } from 'react';
import { Button, Flex, Segmented } from 'antd';
const Demo: React.FC = () => {
const [options, setOptions] = useState(['Daily', 'Weekly', 'Monthly']);
const [moreLoaded, setMoreLoaded] = useState(false);
const handleLoadOptions = () => {
setOptions((prev) => [...prev, 'Quarterly', 'Yearly']);
setMoreLoaded(true);
};
return (
Load more options
);
};
export default Demo;
```
### Three sizes of Segmented
There are three sizes of a Segmented component: `large` (40px), `medium` (32px), and `small` (24px).
```tsx
import React from 'react';
import { Flex, Segmented } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### With Icon
Set `icon` for Segmented Item.
```tsx
import React from 'react';
import { AppstoreOutlined, BarsOutlined } from '@ant-design/icons';
import { Segmented } from 'antd';
const Demo: React.FC = () => (
},
{ label: 'Kanban', value: 'Kanban', icon: },
]}
/>
);
export default Demo;
```
### With Icon only
Set `icon` without `label` for Segmented Item.
```tsx
import React from 'react';
import { AppstoreOutlined, BarsOutlined } from '@ant-design/icons';
import { Segmented } from 'antd';
const Demo: React.FC = () => (
},
{ value: 'Kanban', icon: },
]}
/>
);
export default Demo;
```
### With name
Passing the `name` property to all `input[type="radio"]` that are in the same Segmented. It is usually used to let the browser see your Segmented as a real "group" and keep the default behavior. For example, using left/right keyboard arrow to change your selection that in the same Segmented.
```tsx
import React from 'react';
import { Segmented } from 'antd';
const Demo: React.FC = () => (
options={['Daily', 'Weekly', 'Monthly', 'Quarterly', 'Yearly']} name="group" />
);
export default Demo;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of the Segmented by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { CloudOutlined, RocketOutlined, ThunderboltOutlined } from '@ant-design/icons';
import { Flex, Segmented } from 'antd';
import type { GetProp, SegmentedProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
padding: 2px;
`,
}));
const styleFn: SegmentedProps['styles'] = (info): GetProp => {
if (info.props.vertical) {
return {
root: {
border: '1px solid #77BEF0',
padding: 4,
width: 100,
},
icon: {
color: '#77BEF0',
},
item: {
textAlign: 'start',
},
};
}
return {};
};
const styles: SegmentedProps['styles'] = {
root: {
padding: 4,
width: 260,
},
};
const options: SegmentedProps['options'] = [
{
label: 'Boost',
value: 'boost',
icon: ,
},
{
label: 'Stream',
value: 'stream',
icon: ,
},
{
label: 'Cloud',
value: 'cloud',
icon: ,
},
];
const App: React.FC = () => {
const segmentedSharedProps: SegmentedProps = {
options,
classNames,
};
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
> This component is available since `antd@4.20.0`
### Segmented
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| block | Option to fit width to its parent\'s width | boolean | false | | × |
| classNames | Customize class for each semantic structure inside the Segmented component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| defaultValue | Default selected value | string \| number | Value of first item in `options` | | × |
| disabled | Disable all segments | boolean | false | | × |
| onChange | The callback function that is triggered when the state changes | function(value: string \| number) | | | × |
| options | Set children optional | string\[] \| number\[] \| SegmentedItemType\[] | [] | | × |
| orientation | Orientation | `horizontal` \| `vertical` | `horizontal` | | × |
| size | The size of the Segmented. | `large` \| `medium` \| `small` | `medium` | | × |
| styles | Customize inline style for each semantic structure inside the Segmented component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| vertical | Orientation. Simultaneously existing with `orientation`, `orientation` takes priority | boolean | `false` | 5.21.0 | × |
| value | Currently selected value | string \| number | | | × |
| shape | shape of Segmented | `default` \| `round` | `default` | 5.24.0 | × |
| name | The `name` property of all `input[type="radio"]` children. if not set, it will fallback to a randomly generated name | string | | 5.23.0 | × |
### SegmentedItemType
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| disabled | Disabled state of segmented item | boolean | false | |
| className | The additional css class | string | - | |
| icon | Display icon for Segmented item | ReactNode | - | |
| label | Display text for Segmented item | ReactNode | - | |
| tooltip | tooltip for Segmented item | string \| [TooltipProps](../tooltip/index.en-US.md#api) | - | |
| value | Value for Segmented item | string \| number | - | |
## Semantic DOM
https://ant.design/components/segmented/semantic.md
## Design Token
## Component Token (Segmented)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| itemActiveBg | Background color of item when active | string | rgba(0,0,0,0.15) |
| itemColor | Text color of item | string | rgba(0,0,0,0.65) |
| itemHoverBg | Background color of item when hover | string | rgba(0,0,0,0.06) |
| itemHoverColor | Text color of item when hover | string | rgba(0,0,0,0.88) |
| itemSelectedBg | Background color of item when selected | string | #ffffff |
| itemSelectedColor | Text color of item when selected | string | rgba(0,0,0,0.88) |
| trackBg | Background of Segmented container | string | #f5f5f5 |
| trackPadding | Padding of Segmented container | string \| number | 2 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadius | Border radius of base components | number | |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| borderRadiusXS | XS size border radius, used in some small border radius components, such as Segmented, Arrow and other components with small border radius. | number | |
| boxShadowTertiary | Control the tertiary box shadow style of an element. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDisabled | Control the color of text in disabled state. | string | |
| controlHeight | The height of the basic controls such as buttons and input boxes in Ant Design | number | |
| controlHeightLG | LG component height | number | |
| controlHeightSM | SM component height | number | |
| controlPaddingHorizontal | Control the horizontal padding of an element. | number | |
| controlPaddingHorizontalSM | Control the horizontal padding of an element with a small-medium size. | number | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeLG | Large font size | number | |
| lineHeight | Line height of text. | number | |
| lineWidth | Border width of base components | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| marginSM | Control the margin of an element, with a medium-small size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseInOut | Preset motion curve. | string | |
| paddingXXS | Control the extra extra small padding of the element. | number | |
---
## select
Source: https://ant.design/components/select.md
---
category: Components
group: Data Entry
title: Select
description: A dropdown menu for displaying choices.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*qGSbQJ0POEsAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*a6ggRInInJ4AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
- A dropdown menu for displaying choices - an elegant alternative to the native `` element.
- Utilizing [Radio](/components/radio/) is recommended when there are fewer total options (less than 5).
- You probably need [AutoComplete](/components/auto-complete/) if you're looking for an input box that can be typed or selected.
## Examples
### Basic Usage
Basic Usage.
```tsx
import React from 'react';
import { Select, Space } from 'antd';
const handleChange = (value: string) => {
console.log(`selected ${value}`);
};
const App: React.FC = () => (
);
export default App;
```
### Select with search field
Search the options while expanded.
```tsx
import React from 'react';
import { Select } from 'antd';
const onChange = (value: string) => {
console.log(`selected ${value}`);
};
const onSearch = (value: string) => {
console.log('search:', value);
};
const App: React.FC = () => (
);
export default App;
```
### Custom Search
Customize search using `filterOption`.
```tsx
import React from 'react';
import { Select } from 'antd';
const App: React.FC = () => (
(option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
}}
placeholder="Select a person"
options={[
{ value: '1', label: 'Jack' },
{ value: '2', label: 'Lucy' },
{ value: '3', label: 'Tom' },
]}
/>
);
export default App;
```
### Multi field search
Use `optionFilterProp` for multi-field search.
```tsx
import React from 'react';
import { Select } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### multiple selection
Multiple selection, selecting from existing items.
```tsx
import React from 'react';
import { Select, Space } from 'antd';
import type { SelectProps } from 'antd';
const options: SelectProps['options'] = [];
for (let i = 10; i < 36; i++) {
options.push({
label: i.toString(36) + i,
value: i.toString(36) + i,
});
}
const handleChange = (value: string[]) => {
console.log(`selected ${value}`);
};
const App: React.FC = () => (
);
export default App;
```
### Sizes
The height of the input field for the select defaults to 32px. If size is set to large, the height will be 40px, and if set to small, 24px.
```tsx
import React, { useState } from 'react';
import { Radio, Select, Space } from 'antd';
import type { ConfigProviderProps, RadioChangeEvent, SelectProps } from 'antd';
type SizeType = ConfigProviderProps['componentSize'];
const options: SelectProps['options'] = [];
for (let i = 10; i < 36; i++) {
options.push({
value: i.toString(36) + i,
label: i.toString(36) + i,
});
}
const handleChange = (value: string | string[]) => {
console.log(`Selected: ${value}`);
};
const App: React.FC = () => {
const [size, setSize] = useState('medium');
const handleSizeChange = (e: RadioChangeEvent) => {
setSize(e.target.value);
};
return (
<>
Large
Medium
Small
>
);
};
export default App;
```
### Custom dropdown options
Use `optionRender` to customize the rendering dropdown options
```tsx
import React from 'react';
import { Select, Space } from 'antd';
const options = [
{
label: 'Happy',
value: 'happy',
emoji: '😄',
desc: 'Feeling Good',
},
{
label: 'Sad',
value: 'sad',
emoji: '😢',
desc: 'Feeling Blue',
},
{
label: 'Angry',
value: 'angry',
emoji: '😡',
desc: 'Furious',
},
{
label: 'Cool',
value: 'cool',
emoji: '😎',
desc: 'Chilling',
},
{
label: 'Sleepy',
value: 'sleepy',
emoji: '😴',
desc: 'Need Sleep',
},
];
const App: React.FC = () => (
{
console.log(`selected ${value}`);
}}
options={options}
optionRender={(option) => (
{option.data.emoji}
{`${option.data.label} (${option.data.desc})`}
)}
/>
);
export default App;
```
### Search with sort
Search the options with sorting.
```tsx
import React from 'react';
import { Select } from 'antd';
const App: React.FC = () => (
(optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase()),
}}
style={{ width: 200 }}
placeholder="Search to Select"
options={[
{
value: '1',
label: 'Not Identified',
},
{
value: '2',
label: 'Closed',
},
{
value: '3',
label: 'Communicated',
},
{
value: '4',
label: 'Identified',
},
{
value: '5',
label: 'Resolved',
},
{
value: '6',
label: 'Cancelled',
},
]}
/>
);
export default App;
```
### Tags
Allow user to select tags from list or input custom tag.
```tsx
import React from 'react';
import { Select } from 'antd';
import type { SelectProps } from 'antd';
const options: SelectProps['options'] = [];
for (let i = 10; i < 36; i++) {
options.push({
value: i.toString(36) + i,
label: i.toString(36) + i,
});
}
const handleChange = (value: string[]) => {
console.log(`selected ${value}`);
};
const App: React.FC = () => (
);
export default App;
```
### Option Group
Using `OptGroup` to group the options.
```tsx
import React from 'react';
import { Select } from 'antd';
const handleChange = (value: string) => {
console.log(`selected ${value}`);
};
const App: React.FC = () => (
manager,
title: 'manager',
options: [
{ label: Jack , value: 'Jack' },
{ label: Lucy , value: 'Lucy' },
],
},
{
label: engineer ,
title: 'engineer',
options: [
{ label: Chloe , value: 'Chloe' },
{ label: Lucas , value: 'Lucas' },
],
},
]}
/>
);
export default App;
```
### coordinate
Coordinating the selection of provinces and cities is a common use case and demonstrates how selection can be coordinated. [Cascader](/components/cascader) component is strongly recommended in this case.
```tsx
import React, { useState } from 'react';
import { Select, Space } from 'antd';
const cityData = {
Zhejiang: ['Hangzhou', 'Ningbo', 'Wenzhou'],
Jiangsu: ['Nanjing', 'Suzhou', 'Zhenjiang'],
};
type CityName = keyof typeof cityData;
const provinceData: CityName[] = ['Zhejiang', 'Jiangsu'];
const App: React.FC = () => {
const [cities, setCities] = useState(cityData[provinceData[0] as CityName]);
const [secondCity, setSecondCity] = useState(cityData[provinceData[0]][0] as CityName);
const handleProvinceChange = (value: CityName) => {
setCities(cityData[value]);
setSecondCity(cityData[value][0] as CityName);
};
const onSecondCityChange = (value: CityName) => {
setSecondCity(value);
};
return (
({ label: province, value: province }))}
/>
({ label: city, value: city }))}
/>
);
};
export default App;
```
### Get value of selected item
As a default behavior, the `onChange` callback can only get the `value` of the selected item. The `labelInValue` prop can be used to get the `label` property of the selected item.
The `label` of the selected item will be packed as an object for passing to the `onChange` callback.
```tsx
import React from 'react';
import { Select } from 'antd';
const handleChange = (value: { value: string; label: React.ReactNode }) => {
console.log(value); // { value: "lucy", key: "lucy", label: "Lucy (101)" }
};
const App: React.FC = () => (
);
export default App;
```
### Automatic tokenization
Try to copy `Lucy,Jack` and paste to the input. Only available in tags and multiple mode.
```tsx
import React from 'react';
import { Select } from 'antd';
import type { SelectProps } from 'antd';
const options: SelectProps['options'] = [];
for (let i = 10; i < 36; i++) {
options.push({
value: i.toString(36) + i,
label: i.toString(36) + i,
});
}
const handleChange = (value: string[]) => {
console.log(`selected ${value}`);
};
const App: React.FC = () => (
);
export default App;
```
### Search and Select Users
A complete multiple select sample with remote search, debounce fetch, ajax callback order flow, and loading state.
```tsx
import React, { useMemo, useRef, useState } from 'react';
import { Avatar, Select, Spin } from 'antd';
import type { SelectProps } from 'antd';
import debounce from 'lodash/debounce';
export interface DebounceSelectProps
extends Omit, 'options' | 'children'> {
fetchOptions: (search: string) => Promise;
debounceTimeout?: number;
}
function DebounceSelect<
ValueType extends {
key?: string;
label: React.ReactNode;
value: string | number;
avatar?: string;
} = any,
>({ fetchOptions, debounceTimeout = 300, ...props }: DebounceSelectProps) {
const [fetching, setFetching] = useState(false);
const [options, setOptions] = useState([]);
const fetchRef = useRef(0);
const debounceFetcher = useMemo(() => {
const loadOptions = (value: string) => {
fetchRef.current += 1;
const fetchId = fetchRef.current;
setOptions([]);
setFetching(true);
fetchOptions(value).then((newOptions) => {
if (fetchId !== fetchRef.current) {
// for fetch callback order
return;
}
setOptions(newOptions);
setFetching(false);
});
};
return debounce(loadOptions, debounceTimeout);
}, [fetchOptions, debounceTimeout]);
return (
: 'No results found'}
{...props}
options={options}
optionRender={(option) => (
{option.data.avatar &&
}
{option.label}
)}
/>
);
}
// Usage of DebounceSelect
interface UserValue {
label: string;
value: string;
avatar?: string;
}
async function fetchUserList(username: string): Promise {
console.log('fetching user', username);
return fetch(`https://660d2bd96ddfa2943b33731c.mockapi.io/api/users/?search=${username}`)
.then((res) => res.json())
.then((res) => {
const results = Array.isArray(res) ? res : [];
return results.map((user) => ({
label: user.name,
value: user.id,
avatar: user.avatar,
}));
})
.catch(() => {
console.log('fetch mock data failed');
return [];
});
}
const App: React.FC = () => {
const [value, setValue] = useState([]);
return (
{
if (Array.isArray(newValue)) {
setValue(newValue);
}
}}
/>
);
};
export default App;
```
### Prefix and Suffix
Custom `prefix` and `suffixIcon`.
```tsx
import React from 'react';
import { MehOutlined, SmileOutlined } from '@ant-design/icons';
import { Select, Space } from 'antd';
const smileIcon = ;
const mehIcon = ;
const handleChange = (value: string | string[]) => {
console.log(`selected ${value}`);
};
const App: React.FC = () => (
);
export default App;
```
### Custom dropdown
Customize the dropdown menu via `popupRender`. If you want to close the dropdown after clicking the custom content, you need to control `open` prop, here is an [codesandbox](https://codesandbox.io/s/ji-ben-shi-yong-antd-4-21-7-forked-gnp4cy?file=/demo.js).
```tsx
import React, { useRef, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, Input, Select, Space } from 'antd';
import type { InputRef } from 'antd';
let index = 0;
const App: React.FC = () => {
const [items, setItems] = useState(['jack', 'lucy']);
const [name, setName] = useState('');
const inputRef = useRef(null);
const onNameChange = (event: React.ChangeEvent) => {
setName(event.target.value);
};
const addItem = (e: React.MouseEvent) => {
e.preventDefault();
setItems([...items, name || `New item ${index++}`]);
setName('');
setTimeout(() => {
inputRef.current?.focus();
}, 0);
};
return (
(
<>
{menu}
e.stopPropagation()}
/>
} onClick={addItem}>
Add item
>
)}
options={items.map((item) => ({ label: item, value: item }))}
/>
);
};
export default App;
```
### Hide Already Selected
Hide already selected options in the dropdown.
```tsx
import React, { useState } from 'react';
import { Select } from 'antd';
const OPTIONS = ['Apples', 'Nails', 'Bananas', 'Helicopters'];
const App: React.FC = () => {
const [selectedItems, setSelectedItems] = useState([]);
const filteredOptions = OPTIONS.filter((o) => !selectedItems.includes(o));
return (
({
value: item,
label: item,
}))}
/>
);
};
export default App;
```
### Variants
Variants of Select, there are four variants: `outlined` `filled` `borderless` and `underlined`.
```tsx
import React from 'react';
import { Flex, Select } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Custom Tag Render
Allows for custom rendering of tags.
```tsx
import React from 'react';
import { Select, Tag } from 'antd';
import type { SelectProps } from 'antd';
type TagRender = SelectProps['tagRender'];
const options: SelectProps['options'] = [
{ value: 'gold' },
{ value: 'lime' },
{ value: 'green' },
{ value: 'cyan' },
];
const tagRender: TagRender = (props) => {
const { label, value, closable, onClose } = props;
const onPreventMouseDown = (event: React.MouseEvent) => {
event.preventDefault();
event.stopPropagation();
};
return (
{label}
);
};
const App: React.FC = () => (
);
export default App;
```
### Custom Selected Label Render
Allows custom rendering of the currently selected label, which can be used for value backfill but the corresponding option is missing and does not want to directly render the value.
```tsx
import React from 'react';
import { Select } from 'antd';
import type { SelectProps } from 'antd';
type LabelRender = SelectProps['labelRender'];
const options = [
{ label: 'gold', value: 'gold' },
{ label: 'lime', value: 'lime' },
{ label: 'green', value: 'green' },
{ label: 'cyan', value: 'cyan' },
];
const labelRender: LabelRender = (props) => {
const { label, value } = props;
if (label) {
return value;
}
return No option match ;
};
const App: React.FC = () => (
);
export default App;
```
### Responsive maxTagCount
Auto collapse to tag with responsive case. Not recommend use in large form case since responsive calculation has a perf cost.
```tsx
import React, { useState } from 'react';
import type { SelectProps } from 'antd';
import { Select, Space, Tooltip } from 'antd';
interface ItemProps {
label: string;
value: string;
}
const options: ItemProps[] = [];
for (let i = 10; i < 36; i++) {
const value = i.toString(36) + i;
options.push({
label: `Long Label: ${value}`,
value,
});
}
const sharedProps: SelectProps = {
mode: 'multiple',
style: { width: '100%' },
options,
placeholder: 'Select Item...',
maxTagCount: 'responsive',
};
const App: React.FC = () => {
const [value, setValue] = useState(['a10', 'c12', 'h17', 'j19', 'k20']);
const selectProps: SelectProps = {
value,
onChange: setValue,
};
return (
(
label).join(', ')}
>
Hover Me
)}
/>
);
};
export default App;
```
### Big Data
Select use [virtual scroll](https://github.com/react-component/virtual-list) which get better performance, turn off it by setting `virtual={false}`.
```tsx
import React from 'react';
import type { SelectProps } from 'antd';
import { Select, Typography } from 'antd';
const { Title } = Typography;
const options: SelectProps['options'] = [];
for (let i = 0; i < 100000; i++) {
const value = `${i.toString(36)}${i}`;
options.push({
label: value,
value,
disabled: i === 10,
});
}
const handleChange = (value: string[]) => {
console.log(`selected ${value}`);
};
const App: React.FC = () => (
<>
{options.length} Items
>
);
export default App;
```
### Status
Add status to Select with `status`, which could be `error` or `warning`.
```tsx
import React from 'react';
import { Select, Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Placement
You can manually specify the position of the popup via `placement`.
```tsx
import React, { useState } from 'react';
import type { RadioChangeEvent, SelectProps } from 'antd';
import { Radio, Select } from 'antd';
type SelectCommonPlacement = SelectProps['placement'];
const App: React.FC = () => {
const [placement, setPlacement] = useState('topLeft');
const placementChange = (e: RadioChangeEvent) => {
setPlacement(e.target.value);
};
return (
<>
topLeft
topRight
bottomLeft
bottomRight
>
);
};
export default App;
```
### Max Count
You can set the `maxCount` prop to control the max number of items can be selected. When the limit is exceeded, the options will become disabled.
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import { Select } from 'antd';
const MAX_COUNT = 3;
const App: React.FC = () => {
const [value, setValue] = React.useState(['Ava Swift']);
const suffix = (
<>
{value.length} / {MAX_COUNT}
>
);
return (
);
};
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Select by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { MehOutlined } from '@ant-design/icons';
import { Flex, Select } from 'antd';
import type { GetProp, SelectProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
border-radius: 8px;
width: 300px;
`,
}));
const options: SelectProps['options'] = [
{ value: 'GuangZhou', label: 'GuangZhou' },
{ value: 'ShenZhen', label: 'ShenZhen' },
];
const stylesObject: SelectProps['styles'] = {
prefix: {
color: '#1890ff',
},
suffix: {
color: '#1890ff',
},
};
const stylesFn: SelectProps['styles'] = ({ props }): GetProp => {
if (props.variant === 'filled') {
return {
prefix: {
color: '#722ed1',
},
suffix: {
color: '#722ed1',
},
popup: {
root: {
border: '1px solid #722ed1',
},
},
};
}
return {};
};
const App: React.FC = () => {
const sharedProps: SelectProps = {
options,
classNames,
prefix: ,
};
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Select props
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| allowClear | Customize clear icon | boolean \| { clearIcon?: ReactNode } | false | 5.8.0: Support object type | 6.4.0 |
| ~~autoClearSearchValue~~ | Whether the current search will be cleared on selecting an item. Only applies when `mode` is set to `multiple` or `tags` | boolean | true | | × |
| ~~bordered~~ | Whether has border style, please use `variant` instead | boolean | true | - | × |
| classNames | Customize class for each semantic structure inside the Select component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.25.0 |
| defaultActiveFirstOption | Whether active first option by default | boolean | true | | × |
| defaultOpen | Initial open state of dropdown | boolean | - | | × |
| defaultValue | Initial selected option | string \| string\[] \| number \| number\[] \| LabeledValue \| LabeledValue\[] | - | | × |
| disabled | Whether disabled select | boolean | false | | × |
| ~~dropdownClassName~~ | The className of dropdown menu, please use `classNames.popup.root` instead | string | - | - | × |
| ~~dropdownMatchSelectWidth~~ | Determine whether the popup menu and the select input are the same width, please use `popupMatchSelectWidth` instead | boolean \| number | true | - | × |
| ~~popupClassName~~ | The className of dropdown menu, use `classNames.popup.root` instead | string | - | 4.23.0 | × |
| popupMatchSelectWidth | Determine whether the popup menu and the select input are the same width. Default set `min-width` same as input. Will ignore when value less than select width. `false` will disable virtual scroll | boolean \| number | true | 5.5.0 | × |
| ~~dropdownRender~~ | Customize dropdown content, use `popupRender` instead | (originNode: ReactNode) => ReactNode | - | | × |
| popupRender | Customize dropdown content | (originNode: ReactNode) => ReactNode | - | 5.25.0 | × |
| ~~dropdownStyle~~ | The style of dropdown menu, use `styles.popup.root` instead | CSSProperties | - | | × |
| fieldNames | Customize node label, value, options,groupLabel field name | object | { label: `label`, value: `value`, options: `options`, groupLabel: `label` } | 4.17.0 (`groupLabel` added in 5.6.0) | × |
| ~~filterOption~~ | If true, filter options by input, if function, filter options against it. The function will receive two arguments, `inputValue` and `option`, if the function returns `true`, the option will be included in the filtered set; Otherwise, it will be excluded | boolean \| function(inputValue, option) | true | | × |
| ~~filterSort~~ | Sort function for search options sorting, see [Array.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)'s compareFunction | (optionA: Option, optionB: Option, info: { searchValue: string }) => number | - | `searchValue`: 5.19.0 | × |
| getPopupContainer | Parent Node which the selector should be rendered to. Default to `body`. When position issues happen, try to modify it into scrollable content and position it relative. [Example](https://codesandbox.io/s/4j168r7jw0) | function(triggerNode) | () => document.body | | × |
| labelInValue | Whether to embed label in value, turn the format of value from `string` to { value: string, label: ReactNode } | boolean | false | | × |
| listHeight | Config popup height | number | 256 | | × |
| loading | Indicate loading state | boolean | false | | × |
| loadingIcon | Customize the loading icon | ReactNode | ` ` | 6.4.0 | 6.4.0 |
| maxCount | The max number of items can be selected, only applies when `mode` is `multiple` or `tags` | number | - | 5.13.0 | × |
| maxTagCount | Max tag count to show. `responsive` will cost render performance | number \| `responsive` | - | responsive: 4.10 | × |
| maxTagPlaceholder | Placeholder for not showing tags | ReactNode \| function(omittedValues) | - | | × |
| maxTagTextLength | Max tag text length to show | number | - | | × |
| menuItemSelectedIcon | The custom menuItemSelected icon with multiple options | ReactNode | ` ` | | 6.4.0 |
| mode | Set mode of Select | `multiple` \| `tags` | - | | × |
| notFoundContent | Specify content to show when no result matches | ReactNode | `Not Found` | | × |
| open | Controlled open state of dropdown | boolean | - | | × |
| ~~optionFilterProp~~ | Deprecated, see `showSearch.optionFilterProp` | | | | × |
| optionLabelProp | Which prop value of option will render as content of select. [Example](https://codesandbox.io/s/antd-reproduction-template-tk678) | string | `children` | | × |
| options | Select options. Will get better perf than jsx definition | { label, value }\[] | - | | × |
| optionRender | Customize the rendering dropdown options | (option: FlattenOptionData\ , info: { index: number }) => React.ReactNode | - | 5.11.0 | × |
| placeholder | Placeholder of select | ReactNode | - | | × |
| placement | The position where the selection box pops up | `bottomLeft` `bottomRight` `topLeft` `topRight` | bottomLeft | | × |
| prefix | The custom prefix | ReactNode | - | 5.22.0 | × |
| removeIcon | The custom remove icon | ReactNode | ` ` | | 6.4.0 |
| ~~searchValue~~ | The current input "search" text | string | - | | × |
| ~~showArrow~~ | Whether to show the arrow icon, please use `suffixIcon={null}` instead | boolean | true | - | × |
| showSearch | Whether select is searchable | boolean \| [Object](#showsearch) | single: false, multiple: true | Object: 6.0.0 | 6.4.0 |
| size | Size of Select input | `large` \| `medium` \| `small` | `medium` | | × |
| status | Set validation status | 'error' \| 'warning' | - | 4.19.0 | × |
| styles | Customize inline style for each semantic structure inside the Select component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.25.0 |
| suffixIcon | The custom suffix icon. Custom icons will not respond to clicks to open, because the replaced icon may be designed for other interactions. You can use `pointer-events: none` style to bypass | ReactNode | ` ` | | 6.4.0 |
| tagRender | Customize tag render, only applies when `mode` is set to `multiple` or `tags` | (props) => ReactNode | - | | × |
| labelRender | Customize selected label render (LabelInValueType definition see [LabelInValueType](https://github.com/react-component/select/blob/b39c28aa2a94e7754ebc570f200ab5fd33bd31e7/src/Select.tsx#L70)) | (props: LabelInValueType) => ReactNode | - | 5.15.0 | × |
| tokenSeparators | Separator used to tokenize, only applies when `mode="tags"` | string\[] | - | | × |
| value | Current selected option (considered as a immutable array) | string \| string\[] \| number \| number\[] \| LabeledValue \| LabeledValue\[] | - | | × |
| variant | Variants of selector | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 \| `underlined`: 5.24.0 | 5.19.0 |
| virtual | Disable virtual scroll when set to false | boolean | true | 4.1.0 | × |
| onActive | Called when keyboard or mouse interaction occurs | function(value: string \| number \| LabeledValue) | - | | × |
| onBlur | Called when blur | function | - | | × |
| onChange | Called when select an option or input value change | function(value, option:Option \| Array<Option>) | - | | × |
| onClear | Called when clear | function | - | 4.6.0 | × |
| onDeselect | Called when an option is deselected, param is the selected option's value. Only called for `multiple` or `tags`, effective in multiple or tags mode only | function(value: string \| number \| LabeledValue) | - | | × |
| ~~onDropdownVisibleChange~~ | Called when dropdown open, use `onOpenChange` instead | (open: boolean) => void | - | | × |
| onOpenChange | Called when dropdown open | (open: boolean) => void | - | | × |
| onFocus | Called when focus | (event: FocusEvent) => void | - | | × |
| onInputKeyDown | Called when key pressed | (event: KeyboardEvent) => void | - | | × |
| onPopupScroll | Called when dropdown scrolls | (event: UIEvent) => void | - | | × |
| ~~onSearch~~ | Callback function that is fired when input changed | function(value: string) | - | | × |
| onSelect | Called when an option is selected, the params are option's value (or key) and option instance | function(value: string \| number \| LabeledValue, option: Option) | - | | × |
> Note, if you find that the drop-down menu scrolls with the page, or you need to trigger Select in other popup layers, please try to use `getPopupContainer={triggerNode => triggerNode.parentElement}` to fix the drop-down popup rendering node in the parent element of the trigger .
### showSearch
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| autoClearSearchValue | Whether the current search will be cleared on selecting an item. Only applies when `mode` is set to `multiple` or `tags` | boolean | true | |
| filterOption | If true, filter options by input, if function, filter options against it. The function will receive two arguments, `inputValue` and `option`, if the function returns `true`, the option will be included in the filtered set; Otherwise, it will be excluded | boolean \| function(inputValue, option) | true | |
| filterSort | Sort function for search options sorting, see [Array.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)'s compareFunction | (optionA: Option, optionB: Option, info: { searchValue: string }) => number | - | `searchValue`: 5.19.0 |
| optionFilterProp | Which prop value of option will be used for filter if filterOption is true. If `options` is set, it should be set to `label`. When a string[] is provided, multiple fields are searched using OR matching. | string \| string[] | `value` | `string[]`: 6.1.0 |
| searchValue | The current input "search" text | string | - | |
| onSearch | Callback function that is fired when input changed | function(value: string) | - | |
| searchIcon | Customize the search icon | ReactNode | ` ` | 6.4.0 |
### Select Methods
| Name | Description | Version |
| ------- | ------------ | ------- |
| blur() | Remove focus | |
| focus() | Get focus | |
### Option props
| Property | Description | Type | Default | Version |
| --------- | ------------------------------------ | ---------------- | ------- | ------- |
| className | The additional class to option | string | - | |
| disabled | Disable this option | boolean | false | |
| title | `title` attribute of Select Option | string | - | |
| value | Default to filter with this property | string \| number | - | |
### OptGroup props
| Property | Description | Type | Default | Version |
| --------- | ---------------------------------- | --------------- | ------- | ------- |
| key | Group key | string | - | |
| label | Group label | React.ReactNode | - | |
| className | The additional class to option | string | - | |
| title | `title` attribute of Select Option | string | - | |
## Semantic DOM
https://ant.design/components/select/semantic.md
## Design Token
## Component Token (Select)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| activeBorderColor | Active border color | string | #1677ff |
| activeOutlineColor | Active outline color | string | rgba(5,145,255,0.1) |
| clearBg | Background color of clear button | string | #ffffff |
| hoverBorderColor | Hover border color | string | #4096ff |
| multipleItemBg | Background color of multiple tag | string | rgba(0,0,0,0.06) |
| multipleItemBorderColor | Border color of multiple tag | string | transparent |
| multipleItemBorderColorDisabled | Border color of multiple tag when disabled | string | transparent |
| multipleItemColorDisabled | Text color of multiple tag when disabled | string | rgba(0,0,0,0.25) |
| multipleItemHeight | Height of multiple tag | number | 24 |
| multipleItemHeightLG | Height of multiple tag with large size | number | 32 |
| multipleItemHeightSM | Height of multiple tag with small size | number | 16 |
| multipleSelectorBgDisabled | Background color of multiple selector when disabled | string | rgba(0,0,0,0.04) |
| optionActiveBg | Background color when option is active | string | rgba(0,0,0,0.04) |
| optionFontSize | Font size of option | number | 14 |
| optionHeight | Height of option | number | 32 |
| optionLineHeight | Line height of option | LineHeight \| undefined | 1.5714285714285714 |
| optionPadding | Padding of option | Padding \| undefined | 5px 12px |
| optionSelectedBg | Background color when option is selected | string | #e6f4ff |
| optionSelectedColor | Text color when option is selected | string | rgba(0,0,0,0.88) |
| optionSelectedFontWeight | Font weight when option is selected | FontWeight \| undefined | 600 |
| selectorBg | Background color of selector | string | #ffffff |
| showArrowPaddingInlineEnd | Inline end padding of arrow | number | 18 |
| singleItemHeightLG | Height of single selected item with large size | number | 40 |
| zIndexPopup | z-index of dropdown | number | 1050 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadius | Border radius of base components | number | |
| borderRadiusLG | LG size border radius, used in some large border radius components, such as Card, Modal and other components. | number | |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| borderRadiusXS | XS size border radius, used in some small border radius components, such as Segmented, Arrow and other components with small border radius. | number | |
| boxShadowSecondary | Control the secondary box shadow style of an element. | string | |
| colorBgBase | Used to derive the base variable of the background color gradient. In v5, we added a layer of background color derivation algorithm to produce map token of background color. But PLEASE DO NOT USE this Seed Token directly in the code! | string | |
| colorBgContainer | Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. | string | |
| colorBgContainerDisabled | Control the background color of container in disabled state. | string | |
| colorBgElevated | Container background color of the popup layer, in dark mode the color value of this token will be a little brighter than `colorBgContainer`. E.g: modal, pop-up, menu, etc. | string | |
| colorBorder | Default border color, used to separate different elements, such as: form separator, card separator, etc. | string | |
| colorBorderDisabled | Control the border color of the element in the disabled state. | string | |
| colorError | Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. | string | |
| colorErrorAffix | Control the color of form control prefix/suffix in error state. | string | |
| colorErrorBg | The background color of the error state. | string | |
| colorErrorBgHover | The hover state background color of the error state. | string | |
| colorErrorBorderHover | The hover state border color of the error state. | string | |
| colorErrorOutline | Control the outline color of input component in error state. | string | |
| colorErrorText | The default state of the text in the error color. | string | |
| colorFillSecondary | The second level of fill color can outline the shape of the element more clearly, such as Rate, Skeleton, etc. It can also be used as the Hover state of the third level of fill color, such as Table, etc. | string | |
| colorFillTertiary | The third level of fill color is used to outline the shape of the element, such as Slider, Segmented, etc. If there is no emphasis requirement, it is recommended to use the third level of fill color as the default fill color. | string | |
| colorIcon | Weak action. Such as `allowClear` or Alert close button | string | |
| colorIconHover | Weak action hover color. Such as `allowClear` or Alert close button | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorSplit | Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDescription | Control the font color of text description. | string | |
| colorTextDisabled | Control the color of text in disabled state. | string | |
| colorTextPlaceholder | Control the color of placeholder text. | string | |
| colorTextQuaternary | The fourth level of text color is the lightest text color, such as form input prompt text, disabled color text, etc. | string | |
| colorWarning | Used to represent the warning map token, such as Notification, Alert, etc. Alert or Control component(like Input) will use these map tokens. | string | |
| colorWarningAffix | Control the color of form control prefix/suffix in warning state. | string | |
| colorWarningBg | The background color of the warning state. | string | |
| colorWarningBgHover | The hover state background color of the warning state. | string | |
| colorWarningHover | The hover state of the warning color. | string | |
| colorWarningOutline | Control the outline color of input component in warning state. | string | |
| controlHeight | The height of the basic controls such as buttons and input boxes in Ant Design | number | |
| controlHeightLG | LG component height | number | |
| controlHeightSM | SM component height | number | |
| controlItemBgActiveHover | Control the background color of control component item when hovering and active. | string | |
| controlOutlineWidth | Control the outline width of input component. | number | |
| controlPaddingHorizontal | Control the horizontal padding of an element. | number | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeIcon | Control the font size of operation icon in Select, Cascader, etc. Normally same as fontSizeSM. | number | |
| fontSizeLG | Large font size | number | |
| fontSizeSM | Small font size | number | |
| lineHeight | Line height of text. | number | |
| lineHeightLG | Line height of large text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| motionEaseInOut | Preset motion curve. | string | |
| motionEaseInOutCirc | Preset motion curve. | string | |
| motionEaseInQuint | Preset motion curve. | string | |
| motionEaseOutCirc | Preset motion curve. | string | |
| motionEaseOutQuint | Preset motion curve. | string | |
| paddingSM | Control the small padding of the element. | number | |
| paddingXS | Control the extra small padding of the element. | number | |
| paddingXXS | Control the extra extra small padding of the element. | number | |
## FAQ
### Why sometimes search will show 2 same option when in `tags` mode? {#faq-tags-mode-duplicate}
It's caused by option with different `label` and `value`. You can use `optionFilterProp="label"` to change filter logic instead.
### When I click elements in popupRender, the select dropdown will not be closed? {#faq-popup-not-close}
You can control it by `open` prop: [codesandbox](https://codesandbox.io/s/ji-ben-shi-yong-antd-4-21-7-forked-gnp4cy?file=/demo.js).
### I don't want dropdown close when click inside `popupRender`? {#faq-popup-keep-open}
Select will close when it lose focus. You can prevent event to handle this:
```tsx
(
{
e.preventDefault();
e.stopPropagation();
}}
>
Some Content
)}
/>
```
### Why sometimes customize Option cause scroll break? {#faq-custom-option-scroll}
Virtual scroll internal set item height as `24px`. You need to adjust `listItemHeight` when your option height is less and `listHeight` config list container height:
```tsx
```
Note: `listItemHeight` and `listHeight` are internal props. Please only modify when necessary.
### Why a11y test report missing `aria-` props? {#faq-aria-attribute}
Select only create a11y auxiliary node when operating on. Please open Select and retry. For `aria-label` & `aria-labelledby` miss warning, please add related prop to Select with your own requirement.
Default virtual scrolling will create a mock element to simulate an accessible binding. If a screen reader needs to fully access the entire list, you can set `virtual={false}` to disable virtual scrolling and the accessibility option will be bound to the actual element.
### Why does clicking close on a custom `tagRender` tag open the dropdown? {#faq-tagrender-dropdown}
If you don't want a drop-down menu to appear automatically after clicking on an element (such as a close icon), you can prevent the `MouseDown` event from propagating on it.
```tsx
{
const { closable, label, onClose } = props;
return (
{label}
{closable ? (
e.stopPropagation()}
onClick={onClose}
className="cursor-pointer"
>
❎
) : null}
);
}}
/>
```
---
## skeleton
Source: https://ant.design/components/skeleton.md
---
category: Components
group: Feedback
title: Skeleton
description: Provide a placeholder while you wait for content to load, or to visualize content that doesn't exist yet.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*uae3QbkNCm8AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*VcjGQLSrYdcAAAAAAAAAAAAADrJ8AQ/original
---
## When To Use
- When a resource needs long time to load.
- When the component contains lots of information, such as List or Card.
- Only works when loading data for the first time.
- Could be replaced by Spin in any situation, but can provide a better user experience.
## Examples
### Basic
Simplest Skeleton usage.
```tsx
import React from 'react';
import { Skeleton } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Complex combination
Complex combination with avatar and multiple paragraphs.
```tsx
import React from 'react';
import { Skeleton } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Active Animation
Display active animation.
```tsx
import React from 'react';
import { Skeleton } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Button/Avatar/Input/Image/Node
Skeleton Button, Avatar, Input, Image and Node.
```tsx
import React, { useState } from 'react';
import { DotChartOutlined } from '@ant-design/icons';
import type { RadioChangeEvent } from 'antd';
import { Divider, Flex, Form, Radio, Skeleton, Space, Switch } from 'antd';
type SizeType = 'large' | 'medium' | 'small';
type ButtonShapeType = 'circle' | 'square' | 'round' | 'default';
type AvatarShapeType = 'circle' | 'square';
const App: React.FC = () => {
const [active, setActive] = useState(false);
const [block, setBlock] = useState(false);
const [size, setSize] = useState('medium');
const [buttonShape, setButtonShape] = useState('default');
const [avatarShape, setAvatarShape] = useState('circle');
const handleActiveChange = (checked: boolean) => {
setActive(checked);
};
const handleBlockChange = (checked: boolean) => {
setBlock(checked);
};
const handleSizeChange = (e: RadioChangeEvent) => {
setSize(e.target.value);
};
const handleShapeButton = (e: RadioChangeEvent) => {
setButtonShape(e.target.value);
};
const handleAvatarShape = (e: RadioChangeEvent) => {
setAvatarShape(e.target.value);
};
return (
Large
Medium
Small
Default
Square
Round
Circle
Square
Circle
);
};
export default App;
```
### Contains sub component
Skeleton contains sub component.
```tsx
import React, { useState } from 'react';
import { Button, Skeleton, Space } from 'antd';
const App: React.FC = () => {
const [loading, setLoading] = useState(false);
const showSkeleton = () => {
setLoading(true);
setTimeout(() => {
setLoading(false);
}, 3000);
};
return (
Ant Design, a design language
We supply a series of design principles, practical patterns and high quality design
resources (Sketch and Axure), to help people create their product prototypes beautifully
and efficiently.
Show Skeleton
);
};
export default App;
```
### List
Use skeleton in list component.
```tsx
import React, { useState } from 'react';
import type Icon from '@ant-design/icons';
import { LikeOutlined, MessageOutlined, StarOutlined } from '@ant-design/icons';
import { Avatar, List, Skeleton, Switch } from 'antd';
interface IconTextProps {
icon: typeof Icon;
text: React.ReactNode;
}
const listData = Array.from({ length: 3 }).map((_, i) => ({
href: 'https://ant.design',
title: `ant design part ${i + 1}`,
avatar: `https://api.dicebear.com/10.x/lorelei/svg?seed=${i}`,
description:
'Ant Design, a design language for background applications, is refined by Ant UED Team.',
content:
'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.',
}));
const IconText: React.FC = ({ icon, text }) => (
<>
{React.createElement(icon, { style: { marginInlineEnd: 8 } })}
{text}
>
);
const App: React.FC = () => {
const [loading, setLoading] = useState(true);
const onChange = (checked: boolean) => {
setLoading(!checked);
};
return (
<>
(
,
,
,
]
: undefined
}
extra={
!loading && (
)
}
>
}
title={{item.title} }
description={item.description}
/>
{item.content}
)}
/>
>
);
};
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Skeleton by passing objects or functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Flex, Skeleton } from 'antd';
import type { GetProp, SkeletonProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classnames = createStaticStyles(({ css }) => ({
root: css`
border-radius: 10px;
padding: 12px;
`,
header: css`
margin-bottom: 12px;
`,
}));
const paragraphStyles = createStaticStyles(({ css }) => ({
paragraph: css`
& > li {
background-color: rgba(229, 243, 254, 0.5);
}
`,
}));
const styles: SkeletonProps['styles'] = {
avatar: {
border: '1px solid #aaa',
},
title: {
border: '1px solid #aaa',
},
};
const stylesFn: SkeletonProps['styles'] = (info): GetProp => {
if (info.props.active) {
return {
root: {
border: '1px solid rgba(229, 243, 254, 0.3)',
},
title: {
backgroundColor: 'rgba(229, 243, 254, 0.5)',
height: 20,
borderRadius: 20,
},
};
}
return {};
};
const App: React.FC = () => {
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Common API
### Skeleton
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| active | Show animation effect | boolean | false | | × |
| avatar | Show avatar placeholder | boolean \| [SkeletonAvatar](#skeletonavatar) | false | | × |
| loading | Display the skeleton when true | boolean | - | | × |
| paragraph | Show paragraph placeholder | boolean \| [SkeletonParagraphProps](#skeletonparagraphprops) | true | | × |
| round | Show paragraph and title radius when true | boolean | false | | × |
| title | Show title placeholder | boolean \| [SkeletonTitleProps](#skeletontitleprops) | true | | × |
#### SkeletonTitleProps
| Property | Description | Type | Default |
| -------- | ---------------------- | ---------------- | ------- |
| width | Set the width of title | number \| string | - |
#### SkeletonParagraphProps
| Property | Description | Type | Default |
| --- | --- | --- | --- |
| rows | Set the row count of paragraph | number | - |
| width | Set the width of paragraph. When width is an Array, it can set the width of each row. Otherwise only set the last row width | number \| string \| Array<number \| string> | - |
### Skeleton.Avatar
| Property | Description | Type | Default |
| --- | --- | --- | --- |
| active | Show animation effect, only valid when used avatar independently | boolean | false |
| shape | Set the shape of avatar | `circle` \| `square` | `circle` |
| size | Set the size of avatar | number \| `large` \| `medium` \| `small` | `medium` |
### Skeleton.Button
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| active | Show animation effect | boolean | false | |
| block | Option to fit button width to its parent width | boolean | false | 4.17.0 |
| shape | Set the shape of button | `circle` \| `round` \| `square` \| `default` | - | |
| size | Set the size of button | `large` \| `medium` \| `small` | `medium` | |
### Skeleton.Input
| Property | Description | Type | Default |
| -------- | --------------------- | ------------------------------ | -------- |
| active | Show animation effect | boolean | false |
| size | Set the size of input | `large` \| `medium` \| `small` | `medium` |
## Semantic DOM
### Skeleton
https://ant.design/components/skeleton/semantic.md
### Skeleton.Element
https://ant.design/components/skeleton/semantic_element.md
## Design Token
## Component Token (Skeleton)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| blockRadius | Border radius of skeleton | number | 4 |
| gradientFromColor | Start color of gradient | string | rgba(0,0,0,0.06) |
| gradientToColor | End color of gradient | string | rgba(0,0,0,0.15) |
| paragraphLiHeight | Line height of paragraph skeleton | number | 16 |
| paragraphMarginTop | Margin top of paragraph skeleton | number | 28 |
| titleHeight | Height of title skeleton | string \| number | 16 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| controlHeight | The height of the basic controls such as buttons and input boxes in Ant Design | number | |
| controlHeightLG | LG component height | number | |
| controlHeightSM | SM component height | number | |
| controlHeightXS | XS component height | number | |
| marginSM | Control the margin of an element, with a medium-small size. | number | |
| padding | Control the padding of the element. | number | |
---
## slider
Source: https://ant.design/components/slider.md
---
category: Components
group: Data Entry
title: Slider
description: A Slider component for displaying current value and intervals in range.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*_4heQaUrFn4AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*XkgXTaudeosAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
Used to input a value within a specified range.
## Examples
### Basic
Basic slider. When `range` is `true`, display as dual thumb mode. When `disable` is `true`, the slider will not be interactable.
```tsx
import React, { useState } from 'react';
import { Slider, Switch } from 'antd';
const App: React.FC = () => {
const [disabled, setDisabled] = useState(false);
const onChange = (checked: boolean) => {
setDisabled(checked);
};
return (
<>
Disabled:
>
);
};
export default App;
```
### Slider with InputNumber
Synchronize with [InputNumber](/components/input-number/) component.
```tsx
import React, { useState } from 'react';
import type { InputNumberProps } from 'antd';
import { Col, InputNumber, Row, Slider, Space } from 'antd';
const IntegerStep: React.FC = () => {
const [inputValue, setInputValue] = useState(1);
const onChange: InputNumberProps['onChange'] = (newValue) => {
setInputValue(newValue as number);
};
return (
);
};
const DecimalStep: React.FC = () => {
const [inputValue, setInputValue] = useState(0);
const onChange: InputNumberProps['onChange'] = (value) => {
if (Number.isNaN(value)) {
return;
}
setInputValue(value as number);
};
return (
);
};
const App: React.FC = () => (
);
export default App;
```
### Slider with icon
You can add an icon beside the slider to make it meaningful.
```css
.icon-wrapper {
position: relative;
padding: 0 30px;
}
.icon-wrapper .anticon {
position: absolute;
top: -2px;
width: 16px;
height: 16px;
color: rgba(0, 0, 0, 0.25);
font-size: 16px;
line-height: 1;
}
.icon-wrapper .icon-wrapper-active {
color: rgba(0, 0, 0, 0.45);
}
.icon-wrapper .anticon:first-child {
inset-inline-start: 0;
}
.icon-wrapper .anticon:last-child {
inset-inline-end: 0;
}
```
```tsx
import React, { useState } from 'react';
import { FrownOutlined, SmileOutlined } from '@ant-design/icons';
import { Slider } from 'antd';
interface IconSliderProps {
max: number;
min: number;
}
const IconSlider: React.FC = (props) => {
const { max, min } = props;
const [value, setValue] = useState(0);
const mid = Number(((max - min) / 2).toFixed(5));
const preColorCls = value >= mid ? '' : 'icon-wrapper-active';
const nextColorCls = value >= mid ? 'icon-wrapper-active' : undefined;
return (
);
};
const App: React.FC = () => ;
export default App;
```
### Customize tooltip
Use `tooltip.formatter` to format content of `Tooltip`. If `tooltip.formatter` is null, hide it.
```tsx
import React from 'react';
import type { SliderSingleProps } from 'antd';
import { Slider } from 'antd';
const formatter: NonNullable['formatter'] = (value) => `${value}%`;
const App: React.FC = () => (
<>
>
);
export default App;
```
### Event
The `onChange` callback function will fire when the user changes the slider's value. The `onChangeComplete` callback function will fire when `mouseup` or `keyup` fired.
```tsx
import React from 'react';
import { Slider } from 'antd';
const onChange = (value: number | number[]) => {
console.log('onChange: ', value);
};
const onChangeComplete = (value: number | number[]) => {
console.log('onChangeComplete: ', value);
};
const App: React.FC = () => (
<>
>
);
export default App;
```
### Graduated slider
Using `marks` property to mark a graduated slider, use `value` or `defaultValue` to specify the position of thumb. When `included` is false, means that different thumbs are coordinative. when `step` is null, valid points will only be marks, `min` and `max`.
```tsx
import React from 'react';
import { Slider } from 'antd';
import type { SliderSingleProps } from 'antd';
const marks: SliderSingleProps['marks'] = {
0: '0°C',
26: '26°C',
37: '37°C',
100: {
style: {
color: '#f50',
},
label: 100°C ,
},
};
const App: React.FC = () => (
<>
included=true
included=false
marks & step
step=null
>
);
export default App;
```
### Vertical
The vertical Slider.
```tsx
import React from 'react';
import { Slider } from 'antd';
import type { SliderSingleProps } from 'antd';
const style: React.CSSProperties = {
display: 'inline-block',
height: 300,
marginInlineStart: 70,
};
const marks: SliderSingleProps['marks'] = {
0: '0°C',
26: '26°C',
37: '37°C',
100: {
style: { color: '#f50' },
label: 100°C ,
},
};
const App: React.FC = () => (
<>
>
);
export default App;
```
### Control visibility of Tooltip
When `tooltip.open` is `true`, ToolTip will always show, if set to `false` the ToolTip will not show, even if dragging or hovering.
```tsx
import React from 'react';
import { Slider } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Reverse
Using `reverse` to render slider reversely.
```tsx
import React, { useState } from 'react';
import { Slider, Switch } from 'antd';
const App: React.FC = () => {
const [reverse, setReverse] = useState(true);
return (
<>
Reversed:
>
);
};
export default App;
```
### Draggable track
Make range track draggable by setting `range.draggableTrack`.
```tsx
import React from 'react';
import { Slider } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Multiple handles
Multiple handles combination.
```tsx
import React from 'react';
import { Slider } from 'antd';
function getGradientColor(percentage: number) {
const startColor = [135, 208, 104];
const endColor = [255, 204, 199];
const midColor = startColor.map((start, i) => {
const end = endColor[i];
const delta = end - start;
return (start + delta * percentage).toFixed(0);
});
return `rgb(${midColor.join(',')})`;
}
const App: React.FC = () => {
const [value, setValue] = React.useState([0, 10, 20]);
const start = value[0] / 100;
const end = value[value.length - 1] / 100;
return (
);
};
export default App;
```
### Dynamic edit nodes
Click to add a node, drag out or press the key to delete the node.
```tsx
import React from 'react';
import { Slider } from 'antd';
const App: React.FC = () => {
const [value, setValue] = React.useState([20, 80]);
return (
);
};
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Sliders by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Flex, Slider } from 'antd';
import type { GetProp, SliderSingleProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
width: 300px;
`,
}));
const classNamesFn = createStaticStyles(({ css, cssVar }) => ({
root: css`
width: 100px;
&:hover .ant-slider-handle:after {
box-shadow: 0 0 0 ${cssVar.lineWidthBold} #722ed1;
}
`,
handle: css`
&.ant-slider-handle:hover::after,
&.ant-slider-handle:active::after,
&.ant-slider-handle:focus::after,
&.ant-slider-handle::after {
box-shadow: 0 0 0 ${cssVar.lineWidthBold} #722ed1;
}
`,
}));
const stylesObject: SliderSingleProps['styles'] = {
track: { backgroundImage: 'linear-gradient(180deg, #91caff, #1677ff)' },
handle: { borderColor: '#1677ff', boxShadow: '0 2px 8px #1677ff' },
};
const stylesFn: SliderSingleProps['styles'] = (
info,
): GetProp => {
if (info.props.orientation === 'vertical') {
return {
root: { height: 300 },
track: { backgroundImage: 'linear-gradient(180deg, #722cc0, #722ed1)' },
handle: { borderColor: '#722ed1', boxShadow: '0 2px 8px #722ed1' },
};
}
return {};
};
const App: React.FC = () => {
const sharedProps: SliderSingleProps = {
defaultValue: 30,
};
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.23.0 |
| defaultValue | The default value of the slider. When `range` is false, use number, otherwise, use \[number, number] | number \| \[number, number] | 0 \| \[0, 0] | | × |
| disabled | If true, the slider will not be interactive | boolean | false | | × |
| keyboard | Support using keyboard to move handlers | boolean | true | 5.2.0+ | × |
| dots | Whether the thumb can only be dragged to tick marks | boolean | false | | × |
| included | Takes effect when `marks` is not null. True means containment and false means coordinative | boolean | true | | × |
| marks | Tick marks of Slider. The type of key must be `number`, and must be in closed interval \[min, max]. Each mark can declare its own style | object | { number: ReactNode } \| { number: { style: CSSProperties, label: ReactNode } } | | × |
| max | The maximum value the slider can slide to | number | 100 | | × |
| min | The minimum value the slider can slide to | number | 0 | | × |
| orientation | Orientation | `horizontal` \| `vertical` | `horizontal` | | × |
| range | Enable dual thumb mode for range selection | boolean | false | | × |
| reverse | Reverse the component | boolean | false | | × |
| step | The granularity the slider can step through values. Must be greater than 0, and be divisible by (max - min). When `step` is `null` and `marks` exist, valid points will only be marks, `min` and `max` | number \| null | 1 | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.23.0 |
| tooltip | The tooltip related props | [tooltip](#tooltip) | - | 4.23.0 | × |
| value | The value of slider. When `range` is false, use number, otherwise, use \[number, number] | number \| \[number, number] | - | | × |
| vertical | If true, the slider will be vertical. Simultaneously existing with `orientation`, `orientation` takes priority | boolean | false | | × |
| onChangeComplete | Fire when `mouseup` or `keyup` is fired | (value) => void | - | | × |
| onChange | Callback function that is fired when the user changes the slider's value | (value) => void | - | | × |
| ~~handleStyle~~ | Style of the slider handle, please use `styles.handle` instead | CSSProperties | - | - | × |
| ~~onAfterChange~~ | Callback fired when `mouseup` or `keyup` is fired, please use `onChangeComplete` instead | (value) => void | - | - | × |
| ~~railStyle~~ | Style of the slider rail, please use `styles.rail` instead | CSSProperties | - | - | × |
| ~~trackStyle~~ | Style of the slider track, please use `styles.track` instead | CSSProperties | - | - | × |
### range
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| draggableTrack | Whether range track can be dragged | boolean | false | - |
| editable | Dynamic edit nodes. Cannot be used with `draggableTrack` | boolean | false | 5.20.0 |
| minCount | The minimum count of nodes | number | 0 | 5.20.0 |
| maxCount | The maximum count of nodes | number | - | 5.20.0 |
### tooltip
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| autoAdjustOverflow | Whether to automatically adjust the popup position | boolean | true | 5.8.0 |
| open | If true, Tooltip will always be visible; if false, it will never be visible, even when dragging or hovering | boolean | - | 4.23.0 |
| placement | Set Tooltip display position. Ref [Tooltip](/components/tooltip/) | string | - | 4.23.0 |
| getPopupContainer | The DOM container of the Tooltip. The default behavior is to create a div element in the body | (triggerNode) => HTMLElement | () => document.body | 4.23.0 |
| formatter | Slider will pass its value to `formatter`, display its value in Tooltip, and hide the Tooltip when the returned value is null | value => ReactNode \| null | IDENTITY | 4.23.0 |
## Methods
| Name | Description | Version |
| ------- | ------------ | ------- |
| blur() | Remove focus | |
| focus() | Get focus | |
## Semantic DOM
https://ant.design/components/slider/semantic.md
## Design Token
## Component Token (Slider)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| controlSize | Height of slider | number | 10 |
| dotActiveBorderColor | Border color of dot when active | string | #91caff |
| dotBorderColor | Border color of dot | string | #f0f0f0 |
| dotSize | Size of dot | number | 8 |
| handleActiveColor | Border color of handle when active | string | #1677ff |
| handleActiveOutlineColor | Outline color of handle when active | string | rgba(22,119,255,0.2) |
| handleColor | Color of handle | string | #91caff |
| handleColorDisabled | Color of handle when disabled | string | #bfbfbf |
| handleLineWidth | Border width of handle | string \| number | 2 |
| handleLineWidthHover | Border width of handle when hover | string \| number | 2.5 |
| handleSize | Size of handle | number | 10 |
| handleSizeHover | Size of handle when hover | number | 12 |
| railBg | Background color of rail | string | rgba(0,0,0,0.04) |
| railHoverBg | Background color of rail when hover | string | rgba(0,0,0,0.06) |
| railSize | Height of rail | number | 4 |
| trackBg | Background color of track | string | #91caff |
| trackBgDisabled | Background color of track when disabled | string | rgba(0,0,0,0.04) |
| trackHoverBg | Background color of track when hover | string | #69b1ff |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadiusXS | XS size border radius, used in some small border radius components, such as Segmented, Arrow and other components with small border radius. | number | |
| colorBgElevated | Container background color of the popup layer, in dark mode the color value of this token will be a little brighter than `colorBgContainer`. E.g: modal, pop-up, menu, etc. | string | |
| colorFillContentHover | Control the style of background color of content area when mouse hovers over it. | string | |
| colorPrimaryBorderHover | The hover state of the stroke color under the main color gradient, which will be used when the stroke Hover of components such as Slider and Button. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDescription | Control the font color of text description. | string | |
| controlHeight | The height of the basic controls such as buttons and input boxes in Ant Design | number | |
| controlHeightLG | LG component height | number | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| lineHeight | Line height of text. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
---
## space
Source: https://ant.design/components/space.md
---
category: Components
group: Layout
title: Space
description: Set components spacing.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*ZiJ3SbOH9SUAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*37T2R6O9oi0AAAAAAAAAAAAADrJ8AQ/original
---
## When To Use
- Avoid components clinging together and set a unified space.
- Use Space.Compact when child form components are compactly connected and the border is collapsed (After version `antd@4.24.0` Supported).
### Difference with Flex component
- Space is used to set the spacing between inline elements. It will add a wrapper element for each child element for inline alignment. Suitable for equidistant arrangement of multiple child elements in rows and columns.
- Flex is used to set the layout of block-level elements. It does not add a wrapper element. Suitable for layout of child elements in vertical or horizontal direction, and provides more flexibility and control.
## Examples
### Basic Usage
Crowded components horizontal spacing.
```tsx
import React from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Button, Popconfirm, Space, Upload } from 'antd';
const App: React.FC = () => (
Space
Button
}>Click to Upload
Confirm
);
export default App;
```
### Vertical Space
Crowded components vertical spacing.
```tsx
import React from 'react';
import { Card, Space } from 'antd';
const App: React.FC = () => (
Card content
Card content
Card content
Card content
Card content
Card content
);
export default App;
```
### Space Size
Use `size` to set the spacing. Three sizes are preset: `small`, `medium`, `large`. You can also customize the spacing. If `size` is not set, the spacing is `small`.
```tsx
import React, { useState } from 'react';
import { Button, Radio, Slider, Space } from 'antd';
import type { ConfigProviderProps } from 'antd';
type SizeType = ConfigProviderProps['componentSize'];
const App: React.FC = () => {
const [size, setSize] = useState('small');
const [customSize, setCustomSize] = React.useState(0);
return (
<>
setSize(e.target.value)}>
{['small', 'medium', 'large', 'customize'].map((item) => (
{item}
))}
{size === 'customize' && (
<>
>
)}
Primary
Default
Dashed
Link
>
);
};
export default App;
```
### Align
Config item align.
```css
.space-align-container {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
}
.space-align-block {
flex: none;
margin: 8px 4px;
padding: 4px;
border: 1px solid #40a9ff;
}
.space-align-block .mock-block {
display: inline-block;
padding: 32px 8px 16px;
background: rgba(150, 150, 150, 0.2);
}
```
```tsx
import React from 'react';
import { Button, Space } from 'antd';
const App: React.FC = () => (
center
Primary
Block
start
Primary
Block
end
Primary
Block
baseline
Primary
Block
);
export default App;
```
### Wrap
Auto wrap line.
```tsx
import React from 'react';
import { Button, Space } from 'antd';
const App: React.FC = () => (
{Array.from({ length: 20 }).map((_, index) => (
// eslint-disable-next-line react/no-array-index-key
Button
))}
);
export default App;
```
### separator
Crowded components separator.
```tsx
import React from 'react';
import { Divider, Space, Typography } from 'antd';
const App: React.FC = () => (
}>
Link
Link
Link
);
export default App;
```
### Compact Mode for form component
Compact Mode for form component.
```tsx
import React from 'react';
import { CopyOutlined } from '@ant-design/icons';
import {
AutoComplete,
Button,
Cascader,
ColorPicker,
DatePicker,
Input,
InputNumber,
Select,
Space,
TimePicker,
Tooltip,
TreeSelect,
} from 'antd';
const { TreeNode } = TreeSelect;
const App: React.FC = () => (
Submit
Submit
} />
查询
{}}
>
leaf3} />
Submit
$
$
Button
$
);
export default App;
```
### Button Compact Mode
Button component compact example.
```tsx
import React from 'react';
import {
CommentOutlined,
DownloadOutlined,
EllipsisOutlined,
HeartOutlined,
LikeOutlined,
MailOutlined,
MobileOutlined,
ShareAltOutlined,
StarOutlined,
WarningOutlined,
} from '@ant-design/icons';
import { Button, Dropdown, Space, Tooltip } from 'antd';
const App: React.FC = () => (
} />
} />
} />
} />
} />
} />
,
},
{
key: '2',
label: 'Mail',
icon: ,
},
{
key: '3',
label: 'Mobile',
icon: ,
},
],
}}
trigger={['click']}
>
} />
Button 1
Button 2
Button 3
Button 4
} disabled />
} />
Button 1
Button 2
Button 3
} disabled />
} />
Button 4
} />
);
export default App;
```
### Vertical Compact Mode
Vertical Mode for Space.Compact, support Button only.
```tsx
import React from 'react';
import { Button, Space } from 'antd';
const App: React.FC = () => (
Button 1
Button 2
Button 3
Button 1
Button 2
Button 3
Button 1
Button 2
Button 3
Button 1
Button 2
Button 3
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Space by passing objects/functions through `classNames` and `styles`.
```tsx
import * as React from 'react';
import { Button, Space } from 'antd';
import type { GetProp, SpaceProps } from 'antd';
const classNamesObject: SpaceProps['classNames'] = {
root: 'demo-space-root',
item: 'demo-space-item',
separator: 'demo-space-separator',
};
const classNamesFn: SpaceProps['classNames'] = (
info,
): GetProp => {
if (info.props.orientation === 'vertical') {
return {
root: 'demo-space-root--vertical',
};
} else {
return {
root: 'demo-space-root--horizontal',
};
}
};
const stylesObject: SpaceProps['styles'] = {
root: { borderWidth: 2, borderStyle: 'dashed', padding: 8, marginBottom: 10 },
item: { backgroundColor: '#f0f0f0', padding: 4 },
separator: { color: 'red', fontWeight: 'bold' },
};
const stylesFn: SpaceProps['styles'] = (info): GetProp => {
if (info.props.size === 'large') {
return {
root: {
backgroundColor: '#e6f7ff',
borderColor: '#1890ff',
padding: 8,
},
};
} else {
return {
root: {
backgroundColor: '#fff7e6',
borderColor: '#fa8c16',
},
};
}
};
const App: React.FC = () => {
return (
Styled Button 1
Styled Button 2
Styled Button 3
Large Space Button 1
Large Space Button 2
Large Space Button 3
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Space
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| align | Align items | `start` \| `end` \|`center` \|`baseline` | - | 4.2.0 | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props: SpaceProps })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.6.0 |
| ~~direction~~ | The space direction | `vertical` \| `horizontal` | `horizontal` | 4.1.0 | × |
| orientation | The space direction | `vertical` \| `horizontal` | `horizontal` | | × |
| size | The space size | [Size](#size) \| [Size\[\]](#size) | `small` | 4.1.0 \| Array: 4.9.0 | 5.6.0 |
| ~~split~~ | Set split, please use `separator` instead | ReactNode | - | 4.7.0 | × |
| separator | Set separator | ReactNode | - | - | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props: SpaceProps })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.6.0 |
| vertical | Orientation, Simultaneously configure with `orientation` and prioritize `orientation` | boolean | false | - | × |
| wrap | Auto wrap line, when `horizontal` effective | boolean | false | 4.9.0 | × |
### Size
`'small' | 'middle' | 'large' | number`
### Space.Compact
Use Space.Compact when child form components are compactly connected and the border is collapsed. The supported components are:
- Button
- AutoComplete
- Cascader
- DatePicker
- Input/Input.Search
- InputNumber
- Select
- TimePicker
- TreeSelect
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| block | Option to fit width to its parent\'s width | boolean | false | 4.24.0 |
| ~~direction~~ | Set direction of layout | `vertical` \| `horizontal` | `horizontal` | 4.24.0 |
| orientation | Set direction of layout | `vertical` \| `horizontal` | `horizontal` | |
| vertical | Orientation, Simultaneously configure with `orientation` and prioritize `orientation` | boolean | false | - |
| size | Set child component size | `large` \| `medium` \| `small` | `medium` | 4.24.0 |
### Space.Addon
> This component is available since `antd@5.29.0`.
Used to create custom cells in compact layouts.
| Property | Description | Type | Default | Version |
| -------- | -------------- | --------- | ------- | ------- |
| children | Custom content | ReactNode | - | 5.29.0 |
## Semantic DOM
https://ant.design/components/space/semantic.md
## Design Token
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| padding | Control the padding of the element. | number | |
| paddingLG | Control the large padding of the element. | number | |
| paddingXS | Control the extra small padding of the element. | number | |
---
## spin
Source: https://ant.design/components/spin.md
---
category: Components
group: Feedback
title: Spin
description: Used for the loading status of a page or a block.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*5mC5TomY4B0AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*i43_ToFrL8YAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
When part of the page is waiting for asynchronous data or during a rendering process, an appropriate loading animation can effectively alleviate users' inquietude.
## Examples
### Basic Usage
A simple loading status.
```tsx
import React from 'react';
import { Spin } from 'antd';
const App: React.FC = () => ;
export default App;
```
### Size
A small `Spin` is used for loading text, default sized `Spin` for loading a card-level block, and large `Spin` used for loading a **page**.
```tsx
import React from 'react';
import { Flex, Spin } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### Embedded mode
Embedding content into `Spin` will set it into loading state.
```tsx
import React from 'react';
import { Alert, Flex, Spin, Switch } from 'antd';
const App: React.FC = () => {
const [loading, setLoading] = React.useState(false);
return (
Loading state:
);
};
export default App;
```
### Customized description
Customize the description text.
```tsx
import React from 'react';
import { Alert, Flex, Spin } from 'antd';
const contentStyle: React.CSSProperties = {
padding: 50,
background: 'rgba(0, 0, 0, 0.05)',
borderRadius: 4,
};
const content =
;
const App: React.FC = () => (
{content}
{content}
{content}
);
export default App;
```
### Delay
Specifies a delay for loading state. If `spinning` ends during delay, loading status won't appear.
```tsx
import React from 'react';
import { Alert, Flex, Spin, Switch } from 'antd';
const App: React.FC = () => {
const [loading, setLoading] = React.useState(false);
return (
Loading state:
);
};
export default App;
```
### Custom spinning indicator
Use custom loading indicator.
```tsx
import React from 'react';
import { LoadingOutlined } from '@ant-design/icons';
import { Flex, Spin } from 'antd';
const App: React.FC = () => (
} size="small" />
} />
} size="large" />
} />
);
export default App;
```
### Progress
Show the progress. When `percent="auto"` is set, an indeterminate progress will be displayed.
```tsx
import React from 'react';
import { Flex, Spin, Switch } from 'antd';
const App: React.FC = () => {
const [auto, setAuto] = React.useState(false);
const [percent, setPercent] = React.useState(-50);
const timerRef = React.useRef>(null);
React.useEffect(() => {
timerRef.current = setTimeout(() => {
setPercent((v) => {
const nextPercent = v + 5;
return nextPercent > 150 ? -50 : nextPercent;
});
}, 100);
return () => {
if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
};
}, [percent]);
const mergedPercent = auto ? 'auto' : percent;
return (
{
setAuto(!auto);
setPercent(-50);
}}
/>
);
};
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Spin by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Flex, Spin } from 'antd';
import type { GetProp, SpinProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
padding: 8px;
`,
}));
const stylesObject: SpinProps['styles'] = {
indicator: {
color: '#00d4ff',
},
};
const stylesFn: SpinProps['styles'] = ({ props }): GetProp => {
if (props.size === 'small') {
return {
indicator: {
color: '#722ed1',
},
};
}
return {};
};
const App: React.FC = () => {
const sharedProps: SpinProps = {
spinning: true,
percent: 0,
classNames: { root: classNames.root },
};
return (
);
};
export default App;
```
### Fullscreen
The `fullscreen` mode is perfect for creating page loaders. It adds a dimmed overlay with a centered spinner.
```tsx
import React from 'react';
import { Button, Spin } from 'antd';
const App: React.FC = () => {
const [spinning, setSpinning] = React.useState(false);
const [percent, setPercent] = React.useState(0);
const showLoader = () => {
setSpinning(true);
let ptg = -10;
const interval = setInterval(() => {
ptg += 5;
setPercent(ptg);
if (ptg > 120) {
clearInterval(interval);
setSpinning(false);
setPercent(0);
}
}, 100);
};
return (
<>
Show fullscreen
>
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| delay | Specifies a delay in milliseconds for loading state (prevent flush) | number (milliseconds) | - | | × |
| description | Customize description content | ReactNode | - | 6.3.0 | × |
| fullscreen | Display a backdrop with the `Spin` component | boolean | false | 5.11.0 | × |
| indicator | React node of the spinning indicator | ReactNode | - | | 5.20.0 |
| percent | The progress percentage, when set to `auto`, it will be an indeterminate progress | number \| 'auto' | - | 5.18.0 | × |
| size | The size of Spin, options: `small`, `medium` and `large` | string | `medium` | | × |
| spinning | Whether Spin is visible | boolean | true | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| ~~tip~~ | Customize description content when Spin has children. Deprecated, use `description` instead | ReactNode | - | | × |
| ~~wrapperClassName~~ | The className of wrapper when Spin has children. Deprecated, use `classNames.root` instead | string | - | | × |
### Static Method
- `Spin.setDefaultIndicator(indicator: ReactNode)`
You can define default spin element globally.
## Semantic DOM
https://ant.design/components/spin/semantic.md
## Design Token
## Component Token (Spin)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| contentHeight | Height of content area | string \| number | 400 |
| dotSize | Loading icon size | number | 20 |
| dotSizeLG | Large loading icon size | number | 32 |
| dotSizeSM | Small loading icon size | number | 14 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorBgContainer | Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. | string | |
| colorBgMask | The background color of the mask, used to cover the content below the mask, Modal, Drawer, Image and other components use this token | string | |
| colorFillSecondary | The second level of fill color can outline the shape of the element more clearly, such as Rate, Skeleton, etc. It can also be used as the Hover state of the third level of fill color, such as Table, etc. | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDescription | Control the font color of text description. | string | |
| colorTextLightSolid | Control the highlight color of text with background color, such as the text in Primary Button components. | string | |
| colorWhite | Pure white color don't changed by theme | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| lineHeight | Line height of text. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| paddingSM | Control the small padding of the element. | number | |
| zIndexPopupBase | Base zIndex of component like FloatButton, Affix which can be cover by large popup | number | |
---
## splitter
Source: https://ant.design/components/splitter.md
---
category: Components
group: Layout
title: Splitter
description: Resizable split panel layout
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*f0SISaETY0wAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*y92yRYhObU8AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 1
---
## When To Use
Can be used to separate areas horizontally or vertically. When you need to freely drag and adjust the size of each area. When you need to specify the maximum and minimum width and height of an area.
## Examples
### Basic
Initialize panel size, panel size limit.
```tsx
import React from 'react';
import { Flex, Splitter, Typography } from 'antd';
export const Desc: React.FC> = (props) => (
{props.text}
);
const App: React.FC = () => (
);
export default App;
```
### Control mode
Control the size of the splitter. When one of the panels disables `resizable`, dragging will be disabled.
```tsx
import React from 'react';
import { Button, Flex, Splitter, Switch, Typography } from 'antd';
const Desc: React.FC> = (props) => (
{props.text}
);
const App: React.FC = () => {
const [sizes, setSizes] = React.useState<(number | string)[]>(['50%', '50%']);
const [enabled, setEnabled] = React.useState(true);
return (
setEnabled(!enabled)}
checkedChildren="Enabled"
unCheckedChildren="Disabled"
/>
setSizes(['50%', '50%'])}>Reset
);
};
export default App;
```
### Vertical
Use vertical layout.
```tsx
import React from 'react';
import { Flex, Splitter, Typography } from 'antd';
const Desc: React.FC> = (props) => (
{props.text}
);
const App: React.FC = () => (
);
export default App;
```
### Collapsible
Set `collapsible` to enable collapse. Can through `min` to limit dragging to expand when collapsed.
```tsx
import React, { useState } from 'react';
import { Flex, Splitter, Switch, Typography } from 'antd';
import type { SplitterProps } from 'antd';
const Desc: React.FC> = (props) => (
{props.text}
);
const CustomSplitter: React.FC> = ({ style, ...restProps }) => (
);
const App: React.FC = () => {
const [motion, setMotion] = useState(true);
return (
);
};
export default App;
```
### Control collapsible icons
Set `collapsible.showCollapsibleIcon` to control the display mode of collapsible icons.
```tsx
import React, { useState } from 'react';
import { Flex, Radio, Splitter, Typography } from 'antd';
import type { RadioChangeEvent } from 'antd';
import type { CheckboxGroupProps } from 'antd/es/checkbox';
const Desc: React.FC> = (props) => (
{props.text}
);
const options: CheckboxGroupProps<'auto' | boolean>['options'] = [
{ label: 'Auto', value: 'auto' },
{ label: 'True', value: true },
{ label: 'False', value: false },
];
const App: React.FC = () => {
const [showIconMode, setShowIconMode] = useState<'auto' | boolean>(true);
const onChange = (e: RadioChangeEvent) => {
setShowIconMode(e.target.value);
};
return (
ShowCollapsibleIcon:
);
};
export default App;
```
### Multiple panels
Multiple panels.
```tsx
import React from 'react';
import { Flex, Splitter, Typography } from 'antd';
const Desc: React.FC> = (props) => (
Panel {props.text}
);
const App: React.FC = () => (
);
export default App;
```
### Complex combination
Complex combination panel, quick folding, prohibited from changing size
```tsx
import React from 'react';
import { Flex, Splitter, Typography } from 'antd';
const Desc: React.FC> = (props) => (
{props.text}
);
const App: React.FC = () => (
);
export default App;
```
### Lazy
Lazy mode, dragging does not update the size immediately, but updates when released.
```tsx
import React from 'react';
import { Flex, Space, Splitter, Typography } from 'antd';
const Desc: React.FC> = (props) => (
{props.text}
);
const App: React.FC = () => (
);
export default App;
```
### Customize
customize handle elements and style
```tsx
import React from 'react';
import {
CaretDownOutlined,
CaretLeftOutlined,
CaretRightOutlined,
CaretUpOutlined,
ColumnWidthOutlined,
} from '@ant-design/icons';
import { ConfigProvider, Divider, Flex, Splitter, Typography } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
dragger: {
'&::before': {
backgroundColor: 'transparent !important',
border: `1px dashed ${token.controlItemBgHover}`,
},
'&:hover::before': {
border: `1px dashed ${token.colorPrimary}`,
},
},
draggerActive: {
'&::before': {
border: `1px dashed ${token.colorPrimary}`,
},
},
draggerIcon: {
'&:hover': {
color: token.colorPrimary,
},
},
collapsibleIcon: {
fontSize: 16,
color: token.colorTextDescription,
'&:hover': {
color: token.colorPrimary,
},
},
}));
const Desc: React.FC> = (props) => (
{props.text}
);
const App: React.FC = () => {
const { styles } = useStyles();
return (
}
collapsible={{
icon: {
start: ,
end: ,
},
}}
>
,
end: ,
},
}}
>
);
};
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Splitter by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Flex, Splitter, Typography } from 'antd';
import type { GetProp, SplitterProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const Desc: React.FC> = (
props,
) => {
return (
{props.text}
);
};
const styles = createStaticStyles(({ css, cssVar }) => ({
boxShadow: css`
box-shadow: ${cssVar.boxShadowSecondary};
`,
}));
const stylesObject: SplitterProps['styles'] = {
root: { backgroundColor: '#fffbe6' },
// dragger: { backgroundColor: 'rgba(194,223,252,0.4)' },
dragger: { default: { backgroundColor: 'rgba(194,223,252,0.4)' } },
};
const stylesFn: SplitterProps['styles'] = ({
props,
}): GetProp => {
if (props.orientation === 'horizontal') {
return {
root: {
borderWidth: 2,
borderStyle: 'dashed',
marginBottom: 10,
},
};
}
return {};
};
const App: React.FC = () => {
const splitSharedProps: SplitterProps = {
style: { height: 200 },
classNames: { root: styles.boxShadow },
};
return (
);
};
export default App;
```
### Double-clicked reset
Double-click the dragger to reset the Splitter.Panel to its default size.
```tsx
import React, { useState } from 'react';
import { Flex, Splitter, Typography } from 'antd';
const defaultSizes = ['30%', '40%', '30%'];
const Desc: React.FC> = (props) => (
Panel {props.text}
);
const App: React.FC = () => {
const [sizes, setSizes] = useState<(number | string)[]>(defaultSizes);
const handleDoubleClick = () => {
setSizes(defaultSizes);
};
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
> The Splitter component needs to calculate the panel size through its child elements, so its child elements only support `Splitter.Panel`.
### Splitter
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | 6.0.0 | 6.0.0 |
| collapsible | `motion` to enable collapse animation, `icon` to customize collapse icons | `{ motion?: boolean; icon?: { start?: ReactNode; end?: ReactNode } }` | - | 6.4.0 | × |
| ~~collapsibleIcon~~ | custom collapsible icon | `{start?: ReactNode; end?: ReactNode}` | - | 6.0.0 | × |
| destroyOnHidden | Destroy panel content when collapsed (size is 0). Applies to all panels, can be overridden per panel | `boolean` | `false` | 6.4.0 | × |
| draggerIcon | custom dragger icon | `ReactNode` | - | 6.0.0 | × |
| ~~layout~~ | Layout direction | `horizontal` \| `vertical` | `horizontal` | - | × |
| lazy | Lazy mode | `boolean` | `false` | 5.23.0 | × |
| onCollapse | Callback when expanding or collapsing | `(collapsed: boolean[], sizes: number[]) => void` | - | 5.28.0 | × |
| orientation | Orientation direction | `horizontal` \| `vertical` | `horizontal` | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | 6.0.0 | 6.0.0 |
| vertical | Orientation. Simultaneously existing with `orientation`, `orientation` takes priority | boolean | `false` | | × |
| onDraggerDoubleClick | Callback triggered when the dragger is double-clicked | `(index: number) => void` | - | 6.3.0 | × |
| onResize | Panel size change callback | `(sizes: number[]) => void` | - | - | × |
| onResizeEnd | Drag end callback | `(sizes: number[]) => void` | - | - | × |
| onResizeStart | Callback before dragging starts | `(sizes: number[]) => void` | - | - | × |
### Panel
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| collapsible | Quick folding | `boolean \| { start?: boolean; end?: boolean; showCollapsibleIcon?: boolean \| 'auto' }` | `false` | showCollapsibleIcon: 5.27.0 |
| defaultSize | Initial panel size support number for px or 'percent%' usage | `number \| string` | - | - |
| destroyOnHidden | Destroy panel content when collapsed (size is 0). Overrides Splitter's `destroyOnHidden` | `boolean` | - | 6.4.0 |
| max | Maximum threshold support number for px or 'percent%' usage | `number \| string` | - | - |
| min | Minimum threshold support number for px or 'percent%' usage | `number \| string` | - | - |
| resizable | Whether to enable drag and drop | `boolean` | `true` | - |
| size | Controlled panel size support number for px or 'percent%' usage | `number \| string` | - | - |
## Semantic DOM
https://ant.design/components/splitter/semantic.md
## Design Token
---
## statistic
Source: https://ant.design/components/statistic.md
---
category: Components
group: Data Display
title: Statistic
description: Display statistic number.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*YL7PRYNtH-4AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*BPWDRbSYxJ4AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
- When want to highlight some data.
- When want to display statistic data with description.
## Examples
### Basic
Simplest Usage.
```tsx
import React from 'react';
import { Button, Col, Row, Statistic } from 'antd';
const App: React.FC = () => (
Recharge
);
export default App;
```
### Unit
Add unit through `prefix` and `suffix`.
```tsx
import React from 'react';
import { LikeOutlined } from '@ant-design/icons';
import { Col, Row, Statistic } from 'antd';
const App: React.FC = () => (
} />
);
export default App;
```
### Animated number
Animated number with [react-countup](https://www.npmjs.com/package/react-countup).
```tsx
import React from 'react';
import type { StatisticProps } from 'antd';
import { Col, Row, Statistic } from 'antd';
import { createStyles } from 'antd-style';
import CountUp from 'react-countup';
const useStyle = createStyles(({ css }) => {
return {
content: css`
font-variant-numeric: tabular-nums;
`,
};
});
const formatter: StatisticProps['formatter'] = (value) => (
);
const Demo: React.FC = () => {
const { styles } = useStyle();
return (
);
};
export default Demo;
```
### In Card
Display statistic data in Card.
```tsx
import React from 'react';
import { ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons';
import { Card, Col, Row, Statistic } from 'antd';
const App: React.FC = () => (
}
suffix="%"
/>
}
suffix="%"
/>
);
export default App;
```
### Timer
Timer component.
```tsx
import React from 'react';
import type { StatisticTimerProps } from 'antd';
import { Col, Row, Statistic } from 'antd';
import { createStyles } from 'antd-style';
const { Timer } = Statistic;
const useStyle = createStyles(({ css }) => {
return {
content: css`
font-variant-numeric: tabular-nums;
`,
};
});
const deadline = Date.now() + 1000 * 60 * 60 * 24 * 2 + 1000 * 30; // Dayjs is also OK
const before = Date.now() - 1000 * 60 * 60 * 24 * 2 + 1000 * 30;
const tenSecondsLater = Date.now() + 10 * 1000;
const onFinish: StatisticTimerProps['onFinish'] = () => {
console.log('finished!');
};
const onChange: StatisticTimerProps['onChange'] = (val) => {
if (typeof val === 'number' && !Number.isNaN(val) && 4.95 * 1000 < val && val < 5 * 1000) {
console.log('changed!');
}
};
const Demo: React.FC = () => {
const { styles } = useStyle();
return (
);
};
export default Demo;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of the Statistic by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { ArrowUpOutlined } from '@ant-design/icons';
import { Flex, Statistic } from 'antd';
import type { GetProp, StatisticProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
border: 2px dashed #ccc;
padding: 16px;
border-radius: 8px;
`,
}));
const styleFn: StatisticProps['styles'] = ({
props,
}): GetProp => {
const numValue = Number(props.value ?? 0);
const isNegative = Number.isFinite(numValue) && numValue < 0;
if (isNegative) {
return {
title: {
color: '#ff4d4f',
},
content: {
color: '#ff7875',
},
value: {
backgroundColor: '#fff1f0',
borderRadius: 4,
paddingInline: 6,
userSelect: 'none',
},
};
}
return {};
};
const Demo: React.FC = () => {
const statisticSharedProps: StatisticProps = {
classNames: { root: classNames.root },
prefix: ,
};
return (
);
};
export default Demo;
```
## API
Common props ref:[Common props](/docs/react/common-props)
#### Statistic
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | Customize class for each semantic structure inside the Statistic component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| decimalSeparator | The decimal separator | string | `.` | | × |
| formatter | Customize value display logic | (value) => ReactNode | - | | × |
| groupSeparator | Group separator | string | `,` | | × |
| loading | Loading status of Statistic | boolean | false | 4.8.0 | × |
| precision | The precision of input value | number | - | | × |
| prefix | The prefix node of value | ReactNode | - | | × |
| styles | Customize inline style for each semantic structure inside the Statistic component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| suffix | The suffix node of value | ReactNode | - | | × |
| title | Display title | ReactNode | - | | × |
| value | Display value | string \| number | - | | × |
| ~~valueStyle~~ | Set value section style, please use `styles.content` instead | CSSProperties | - | | × |
#### Statistic.Countdown Deprecated
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| format | Format as [dayjs](https://day.js.org/) | string | `HH:mm:ss` | |
| prefix | The prefix node of value | ReactNode | - | |
| suffix | The suffix node of value | ReactNode | - | |
| title | Display title | ReactNode | - | |
| value | Set target countdown time | number | - | |
| valueStyle | Set value section style | CSSProperties | - | |
| onFinish | Trigger when time's up | () => void | - | |
| onChange | Trigger when time's changing | (value: number) => void | - | 4.16.0 |
#### Statistic.Timer 5.25.0+
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| type | Timer direction, count down or count up | `countdown` \| `countup` | - | |
| format | Format as [dayjs](https://day.js.org/) | string | `HH:mm:ss` | |
| prefix | The prefix node of value | ReactNode | - | |
| suffix | The suffix node of value | ReactNode | - | |
| title | Display title | ReactNode | - | |
| value | Target time for `countdown`, or start time for `countup` (timestamp in ms) | number | - | |
| valueStyle | Set value section style | CSSProperties | - | |
| onFinish | Trigger when time's up, only called when type is `countdown` | () => void | - | |
| onChange | Trigger when time's changing | (value: number) => void | - | |
## Semantic DOM
Statistic supports `root`, `header`, `title`, `content`, `value`, `prefix`, and `suffix` semantic DOM nodes.
https://ant.design/components/statistic/semantic.md
## Design Token
## Component Token (Statistic)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| contentFontSize | Content font size | string \| number | 24 |
| titleFontSize | Title font size | number | 14 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDescription | Control the font color of text description. | string | |
| colorTextHeading | Control the font color of heading. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| lineHeight | Line height of text. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
| padding | Control the padding of the element. | number | |
---
## steps
Source: https://ant.design/components/steps.md
---
category: Components
group: Navigation
title: Steps
description: A navigation bar that guides users through the steps of a task.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*677sTqCpE3wAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*cFsBQLA0b7UAAAAAAAAAAAAADrJ8AQ/original
---
## When To Use
When a given task is complicated or has a certain sequence in the series of subtasks, we can decompose it into several steps to make things easier.
## Examples
### Basic
The most basic step bar. Use the `variant` property to set different styles and `size` to control the size.
```tsx
import React from 'react';
import { Flex, Steps } from 'antd';
const content = 'This is a content.';
const items = [
{
title: 'Finished',
content,
},
{
title: 'In Progress',
content,
subTitle: 'Left 00:00:08',
},
{
title: 'Waiting',
content,
},
];
const App: React.FC = () => (
);
export default App;
```
### Error status
By using `status` of `Steps`, you can specify the state for current step.
```tsx
import React from 'react';
import { Steps } from 'antd';
const content = 'This is a content';
const items = [
{
title: 'Finished',
content,
},
{
title: 'In Process',
content,
},
{
title: 'Waiting',
content,
},
];
const App: React.FC = () => ;
export default App;
```
### Vertical
A simple step bar in the vertical orientation.
```tsx
import React from 'react';
import { Flex, Steps } from 'antd';
const content = 'This is a content.';
const items = [
{
title: 'Finished',
content,
},
{
title: 'In Progress',
content,
},
{
title: 'Waiting',
content,
},
];
const App: React.FC = () => (
);
export default App;
```
### Clickable
Setting `onChange` makes Steps clickable.
```tsx
import React, { useState } from 'react';
import { Divider, Steps } from 'antd';
const App: React.FC = () => {
const [current, setCurrent] = useState(0);
const onChange = (value: number) => {
console.log('onChange:', value);
setCurrent(value);
};
const content = 'This is a content.';
return (
<>
>
);
};
export default App;
```
### Panel Steps
Panel style steps.
```tsx
import React, { useState } from 'react';
import { Flex, Steps } from 'antd';
import type { StepsProps } from 'antd';
const App: React.FC = () => {
const [current, setCurrent] = useState(0);
const onChange = (value: number) => {
console.log('onChange:', value);
setCurrent(value);
};
const sharedProps: StepsProps = {
type: 'panel',
current,
onChange,
items: [
{
title: 'Step 1',
subTitle: '00:00',
content: 'This is a content.',
},
{
title: 'Step 2',
content: 'This is a content.',
status: 'error',
},
{
title: 'Step 3',
content: 'This is a content.',
},
],
};
return (
);
};
export default App;
```
### With icon
You can use your own custom icons by setting the property `icon` for `items`.
```tsx
import React from 'react';
import { LoadingOutlined, SmileOutlined, SolutionOutlined, UserOutlined } from '@ant-design/icons';
import { Steps } from 'antd';
const App: React.FC = () => (
,
},
{
title: 'Verification',
status: 'finish',
icon: ,
},
{
title: 'Pay',
status: 'process',
icon: ,
},
{
title: 'Done',
status: 'wait',
icon: ,
},
]}
/>
);
export default App;
```
### Title Placement and Progress
Use `titlePlacement` to set the label position and display the progress through `percent`.
```tsx
import React from 'react';
import { Steps } from 'antd';
const content = 'This is a content.';
const items = [
{
title: 'Finished',
content,
},
{
title: 'In Progress',
content,
},
{
title: 'Waiting',
content,
},
];
const App: React.FC = () => (
<>
>
);
export default App;
```
### Dot Style
Steps with progress dot style.
```tsx
import React from 'react';
import { Divider, Flex, Steps } from 'antd';
import type { StepsProps } from 'antd';
const items = [
{
title: 'Finished',
content: 'This is a content.',
},
{
title: 'In Progress',
content: 'This is a content.',
},
{
title: 'Waiting',
content: 'This is a content.',
},
];
const sharedProps: StepsProps = {
type: 'dot',
current: 1,
items,
};
const sharedVerticalProps = {
...sharedProps,
orientation: 'vertical',
style: {
flex: 'auto',
},
} as const;
const App: React.FC = () => (
);
export default App;
```
### Navigation Steps
Navigation steps.
```tsx
import React, { useState } from 'react';
import { Flex, Steps } from 'antd';
const App: React.FC = () => {
const [current, setCurrent] = useState(0);
const onChange = (value: number) => {
console.log('onChange:', value);
setCurrent(value);
};
return (
);
};
export default App;
```
### Inline Steps
Inline type steps, suitable for displaying the process and current state of the object in the list content scene.
```tsx
import React from 'react';
import type { StepsProps } from 'antd';
import { Avatar, List, Steps } from 'antd';
const data = [
{
title: 'Ant Design Title 1',
current: 0,
},
{
title: 'Ant Design Title 2',
current: 1,
status: 'error',
},
{
title: 'Ant Design Title 3',
current: 2,
},
{
title: 'Ant Design Title 4',
current: 1,
},
];
const items = [
{
title: 'Step 1',
content: 'This is Step 1',
},
{
title: 'Step 2',
content: 'This is Step 2',
},
{
title: 'Step 3',
content: 'This is Step 3',
},
];
const App: React.FC = () => (
(
}
title={{item.title} }
description="Ant Design, a design language for background applications, is refined by Ant UED Team"
/>
)}
/>
);
export default App;
```
### Inline Style Combination
Inline step bar modifies the style and aligns through `offset`.
```tsx
import React from 'react';
import type { StepsProps } from 'antd';
import { Flex, Steps, theme } from 'antd';
const items: StepsProps['items'] = Array.from({ length: 5 }, (_, index) => ({
title: `Step ${index + 1}`,
subTitle: 'Sub Title',
content: `This is Step ${index + 1}`,
}));
const App: React.FC = () => {
const { token } = theme.useToken();
return (
);
};
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Steps by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Flex, Steps } from 'antd';
import type { GetProp, StepsProps } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
root: {
border: `2px dashed ${token.colorBorder}`,
borderRadius: token.borderRadius,
padding: token.padding,
},
}));
const stylesObject: StepsProps['styles'] = {
itemIcon: { borderRadius: '30%' },
itemContent: { fontStyle: 'italic' },
};
const stylesFn: StepsProps['styles'] = (info): GetProp => {
if (info.props.type === 'navigation') {
return {
root: {
borderColor: '#1890ff',
},
};
}
return {};
};
const App: React.FC = () => {
const { styles } = useStyles();
const sharedProps: StepsProps = {
items: [
{ title: 'Finished', content: 'This is a content.' },
{ title: 'In Progress', content: 'This is a content.' },
{ title: 'Waiting', content: 'This is a content.' },
],
current: 1,
classNames: { root: styles.root },
};
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Steps
The whole of the step bar.
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| current | To set the current step, counting from 0. You can overwrite this state by using `status` of `Step` | number | 0 | | × |
| ~~direction~~ | To specify the direction of the step bar, `horizontal` or `vertical` | string | `horizontal` | | × |
| iconRender | Custom render icon, please use `items.icon` first | (oriNode, info: { index, active, item }) => ReactNode | - | | × |
| initial | Set the initial step, counting from 0 | number | 0 | | × |
| ~~labelPlacement~~ | Place title and content with `horizontal` or `vertical` direction | string | `horizontal` | | × |
| orientation | To specify the orientation of the step bar, `horizontal` or `vertical` | string | `horizontal` | | × |
| percent | Progress circle percentage of current step in `process` status (only works on basic Steps) | number | - | 4.5.0 | × |
| ~~progressDot~~ | Steps with progress dot style, customize the progress dot by setting it to a function. Please use `type="dot"` instead. `titlePlacement` will be `vertical` | boolean \| (iconDot, { index, status, title, content }) => ReactNode | false | | × |
| responsive | Change to vertical direction when screen width smaller than `532px` | boolean | true | | × |
| size | To specify the size of the step bar, `medium` and `small` are currently supported | string | `medium` | | × |
| status | To specify the status of current step, can be set to one of the following values: `wait` `process` `finish` `error` | string | `process` | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| titlePlacement | Place title and content with `horizontal` or `vertical` direction | string | `horizontal` | | × |
| type | Type of steps, can be set to one of the following values: `default` `dot` `inline` `navigation` `panel` | string | `default` | | × |
| variant | Config style variant | `filled` \| `outlined` | `filled` | | × |
| onChange | Trigger when Step is changed | (current) => void | - | | × |
| items | StepItem content | [StepItem](#stepitem) | [] | 4.24.0 | × |
### StepItem
A single step in the step bar.
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| content | Description of the step, optional property | ReactNode | - | |
| ~~description~~ | Description of the step, optional property | ReactNode | - | |
| disabled | Disable click | boolean | false | |
| icon | Icon of the step, optional property | ReactNode | - | |
| status | To specify the status. It will be automatically set by `current` of `Steps` if not configured. Optional values are: `wait` `process` `finish` `error` | string | `wait` | |
| subTitle | Subtitle of the step | ReactNode | - | |
| title | Title of the step | ReactNode | - | |
## Semantic DOM
### Steps
https://ant.design/components/steps/semantic.md
### StepItem
https://ant.design/components/steps/semantic_items.md
## Design Token
## Component Token (Steps)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| customIconFontSize | Font size of custom icon | number | 24 |
| customIconSize | Size of custom icon container | number | 32 |
| customIconTop | Top of custom icon | number | 0 |
| dotCurrentSize | Current size of dot | number | 10 |
| dotSize | Size of dot | number | 8 |
| iconFontSize | Size of icon | number | 14 |
| iconSize | Size of icon container | number | 32 |
| iconSizeSM | Size of small steps icon | string \| number | 24 |
| iconTop | Top of icon | number | -0.5 |
| navArrowColor | Color of arrow in nav | string | rgba(0,0,0,0.25) |
| navContentMaxWidth | Max width of nav content | MaxWidth \| undefined | unset |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| borderRadius | Border radius of base components | number | |
| borderRadiusSM | SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size | number | |
| colorBgContainer | Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. | string | |
| colorError | Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. | string | |
| colorErrorBg | The background color of the error state. | string | |
| colorErrorBgFilledHover | The wrong color fills the background color of the suspension state, which is currently only used in the hover effect of the dangerous filled button. | string | |
| colorErrorHover | The hover state of the error color. | string | |
| colorFillTertiary | The third level of fill color is used to outline the shape of the element, such as Slider, Segmented, etc. If there is no emphasis requirement, it is recommended to use the third level of fill color as the default fill color. | string | |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorPrimaryBg | Light background color of primary color, usually used for weak visual level selection state. | string | |
| colorPrimaryBgHover | The hover state color corresponding to the light background color of the primary color. | string | |
| colorPrimaryHover | Hover state under the main color gradient. | string | |
| colorSplit | Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextDescription | Control the font color of text description. | string | |
| colorTextDisabled | Control the color of text in disabled state. | string | |
| colorTextLabel | Control the font color of text label. | string | |
| colorTextLightSolid | Control the highlight color of text with background color, such as the text in Primary Button components. | string | |
| colorTextQuaternary | The fourth level of text color is the lightest text color, such as form input prompt text, disabled color text, etc. | string | |
| colorTextSecondary | The second level of text color is generally used in scenarios where text color is not emphasized, such as label text, menu text selection state, etc. | string | |
| controlHeight | The height of the basic controls such as buttons and input boxes in Ant Design | number | |
| controlItemBgHover | Control the background color of control component item when hovering. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeIcon | Control the font size of operation icon in Select, Cascader, etc. Normally same as fontSizeSM. | number | |
| fontSizeLG | Large font size | number | |
| fontSizeSM | Small font size | number | |
| lineHeight | Line height of text. | number | |
| lineHeightLG | Line height of large text. | number | |
| lineHeightSM | Line height of small text. | number | |
| lineType | Border style of base components | string | |
| lineWidth | Border width of base components | number | |
| lineWidthBold | The default line width of the outline class components, such as Button, Input, Select, etc. | number | |
| margin | Control the margin of an element, with a medium size. | number | |
| marginSM | Control the margin of an element, with a medium-small size. | number | |
| marginXS | Control the margin of an element, with a small size. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| motionDurationSlow | Motion speed, slow speed. Used for large element animation interaction. | string | |
| paddingSM | Control the small padding of the element. | number | |
| paddingXS | Control the extra small padding of the element. | number | |
| paddingXXS | Control the extra extra small padding of the element. | number | |
---
## switch
Source: https://ant.design/components/switch.md
---
category: Components
group: Data Entry
title: Switch
description: Used to toggle between two states.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*rtArRpBNDZcAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*al07RK8SGf4AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## When To Use
- If you need to represent the switching between two states or on-off state.
- The difference between `Switch` and `Checkbox` is that `Switch` will trigger a state change directly when you toggle it, while `Checkbox` is generally used for state marking, which should work in conjunction with submit operation.
## Examples
### Basic
The most basic usage.
```tsx
import React from 'react';
import { Switch } from 'antd';
const onChange = (checked: boolean) => {
console.log(`switch to ${checked}`);
};
const App: React.FC = () => ;
export default App;
```
### Disabled
Disabled state of `Switch`.
```tsx
import React, { useState } from 'react';
import { Button, Space, Switch } from 'antd';
const App: React.FC = () => {
const [disabled, setDisabled] = useState(true);
const toggle = () => {
setDisabled(!disabled);
};
return (
Toggle disabled
);
};
export default App;
```
### Text & icon
With text and icon.
```tsx
import React from 'react';
import { CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { Space, Switch } from 'antd';
const App: React.FC = () => (
}
unCheckedChildren={ }
defaultChecked
/>
);
export default App;
```
### Two sizes
`size="small"` represents a small sized switch.
```tsx
import React from 'react';
import { Switch } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### Loading
Mark a pending state of switch.
```tsx
import React from 'react';
import { Switch } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### Custom semantic dom styling
You can customize the [semantic dom](#semantic-dom) style of Switch by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Flex, Switch } from 'antd';
import type { GetProp, SwitchProps } from 'antd';
import { createStyles } from 'antd-style';
const useStyle = createStyles(({ token }) => ({
root: {
width: 40,
backgroundColor: token.colorPrimary,
},
}));
const stylesObject: SwitchProps['styles'] = {
root: {
backgroundColor: '#F5D2D2',
},
};
const stylesFn: SwitchProps['styles'] = (info): GetProp => {
if (info.props.size === 'medium') {
return {
root: {
backgroundColor: '#BDE3C3',
},
};
}
return {};
};
const App: React.FC = () => {
const { styles: classNames } = useStyle();
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Property | Description | Type | Default | Version | [Global Config](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| checked | Determine whether the Switch is checked | boolean | false | | × |
| checkedChildren | The content to be shown when the state is checked | ReactNode | - | | × |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| defaultChecked | Whether to set the initial state | boolean | false | | × |
| defaultValue | Alias for `defaultChecked` | boolean | - | 5.12.0 | × |
| disabled | Disable switch | boolean | false | | × |
| loading | Loading state of switch | boolean | false | | × |
| size | The size of the Switch, options: `medium` `small` | `'medium'` \| `'small'` | `medium` | | × |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| unCheckedChildren | The content to be shown when the state is unchecked | ReactNode | - | | × |
| value | Alias for `checked` | boolean | - | 5.12.0 | × |
| onChange | Trigger when the checked state is changing | function(checked: boolean, event: Event) | - | | × |
| onClick | Trigger when clicked | function(checked: boolean, event: Event) | - | | × |
## Methods
| Name | Description |
| ------- | ------------ |
| blur() | Remove focus |
| focus() | Get focus |
## Semantic DOM
https://ant.design/components/switch/semantic.md
## Design Token
## Component Token (Switch)
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| handleBg | Background color of Switch handle | string | #fff |
| handleShadow | Shadow of Switch handle | string | 0 2px 4px 0 rgba(0,35,11,0.2) |
| handleSize | Size of Switch handle | number | 18 |
| handleSizeSM | Size of small Switch handle | number | 12 |
| innerMaxMargin | Maximum margin of content area | number | 24 |
| innerMaxMarginSM | Maximum margin of content area of small Switch | number | 18 |
| innerMinMargin | Minimum margin of content area | number | 9 |
| innerMinMarginSM | Minimum margin of content area of small Switch | number | 6 |
| trackHeight | Height of Switch | string \| number | 22 |
| trackHeightSM | Height of small Switch | string \| number | 16 |
| trackMinWidth | Minimum width of Switch | string \| number | 44 |
| trackMinWidthSM | Minimum width of small Switch | string \| number | 28 |
| trackPadding | Padding of Switch | number | 2 |
## Global Token
| Token Name | Description | Type | Default Value |
| --- | --- | --- | --- |
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorPrimaryHover | Hover state under the main color gradient. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextLightSolid | Control the highlight color of text with background color, such as the text in Primary Button components. | string | |
| colorTextQuaternary | The fourth level of text color is the lightest text color, such as form input prompt text, disabled color text, etc. | string | |
| colorTextTertiary | The third level of text color is generally used for descriptive text, such as form supplementary explanation text, list descriptive text, etc. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeIcon | Control the font size of operation icon in Select, Cascader, etc. Normally same as fontSizeSM. | number | |
| fontSizeSM | Small font size | number | |
| lineHeight | Line height of text. | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| opacityLoading | Control the opacity of the loading state. | number | |
## FAQ
### Why not work in Form.Item? {#faq-binding-data}
Form.Item default bind value to `value` property, but Switch value property is `checked`. You can use `valuePropName` to change bind property.
```tsx | pure
```
---
## table
Source: https://ant.design/components/table.md
---
category: Components
group: Data Display
title: Table
description: A table displays rows of data.
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*3yz3QqMlShYAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*Sv8XQ50NB40AAAAAAAAAAAAADrJ8AQ/original
---
## When To Use
- To display a collection of structured data.
- To sort, search, paginate, filter data.
## How To Use
Specify `dataSource` of Table as an array of data.
```jsx
const dataSource = [
{
key: '1',
name: 'Mike',
age: 32,
address: '10 Downing Street',
},
{
key: '2',
name: 'John',
age: 42,
address: '10 Downing Street',
},
];
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
];
;
```
## Promotion
- [Kitchen Sketch Plugin 💎](https://kitchen.alipay.com)
- [ProTable - Advanced Tables](https://procomponents.ant.design/en-US/components/table)
- [S2 - Analytical Tables](https://github.com/antvis/s2/)
## Examples
### Basic Usage
Simple table with actions.
```tsx
import React from 'react';
import { Flex, Space, Table, Tag } from 'antd';
import type { TableProps } from 'antd';
interface DataType {
key: string;
name: string;
age: number;
address: string;
tags: string[];
}
const columns: TableProps['columns'] = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: (text) => {text} ,
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
{
title: 'Tags',
key: 'tags',
dataIndex: 'tags',
render: (_, { tags }) => (
{tags.map((tag) => {
let color = tag.length > 5 ? 'geekblue' : 'green';
if (tag === 'kawaii') {
color = 'volcano';
}
return (
{tag.toUpperCase()}
);
})}
),
},
{
title: 'Action',
key: 'action',
render: (_, record) => (
Invite {record.name}
Delete
),
},
];
const data: DataType[] = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
tags: ['nice', 'developer'],
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
tags: ['kawaii'],
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sydney No. 1 Lake Park',
tags: ['cool', 'teacher'],
},
];
const App: React.FC = () => columns={columns} dataSource={data} />;
export default App;
```
### JSX style API
Using JSX style API (introduced in 2.5.0)
> Since this is just a syntax sugar for the prop `columns`, you can't compose `Column` and `ColumnGroup` with other Components.
```tsx
import React from 'react';
import { Flex, Space, Table, Tag } from 'antd';
const { Column, ColumnGroup } = Table;
interface DataType {
key: React.Key;
firstName: string;
lastName: string;
age: number;
address: string;
tags: string[];
}
const data: DataType[] = [
{
key: '1',
firstName: 'John',
lastName: 'Brown',
age: 32,
address: 'New York No. 1 Lake Park',
tags: ['nice', 'developer'],
},
{
key: '2',
firstName: 'Jim',
lastName: 'Green',
age: 42,
address: 'London No. 1 Lake Park',
tags: ['kawaii'],
},
{
key: '3',
firstName: 'Joe',
lastName: 'Black',
age: 32,
address: 'Sydney No. 1 Lake Park',
tags: ['cool', 'teacher'],
},
];
const App: React.FC = () => (
dataSource={data}>