# Ant Design Component Documentation
This file contains aggregated content from all component docs.
> Total 73 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;
```
---
## 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 (
<>
>
);
};
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)}>
);
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 (
}]}
/>
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:
,
},
];
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:
,
},
];
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:
,
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:
,
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:
,
},
];
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 { Collapse, Flex } from 'antd';
import { createStaticStyles } from 'antd-style';
import type { CollapseProps } from '..';
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 }) => {
if (props.size === 'large') {
return {
root: {
backgroundColor: '#fff',
border: '1px solid #696FC7',
borderRadius: 8,
},
header: {
backgroundColor: '#F5EFFF',
padding: '12px 16px',
color: '#141414',
},
} satisfies CollapseProps['styles'];
}
};
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 |
| --- | --- | --- | --- | --- |
| 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> | - | |
| 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 | Allow to customize collapse icon | (panelProps) => ReactNode | - | |
| 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> | - | |
| 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 (
);
};
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 = () => (
(
Color Picker
{panel}
)}
/>
);
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 } 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) => {
if (info.props.size === 'large') {
return {
popup: {
root: {
border: '1px solid #722ed1',
},
},
} satisfies ColorPickerProps['styles'];
}
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 |
| :-- | :-- | :-- | :-- | :-- |
| allowClear | Allow clearing color selected | boolean | false | |
| arrow | Configuration for popup arrow | `boolean \| { pointAtCenter: boolean }` | true | |
| 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> | - | |
| 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> | - | |
| 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
```
## 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 (
Click to confirm
);
};
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 propsBy 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 } 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) => {
if (info.props.size === 'large') {
return {
root: { borderColor: '#722ed1' },
popup: {
container: { border: '1px solid #722ed1', borderRadius: 8 },
},
} satisfies DatePickerProps['styles'];
}
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 (
<>
topLefttopRightbottomLeftbottomRight
>
);
};
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: local. 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 use with Next.js App Router, make sure to add `'use client'` before import locale file of dayjs. It's because all components of Ant Design only works in client, importing locale in RSC will not work.
:::
### Common API
The following APIs are shared by DatePicker, RangePicker.
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| allowClear | Customize clear button | boolean \| { clearIcon?: ReactNode } | true | 5.8.0: Support object type |
| className | The picker className | string | - | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| 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 |
| 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 | Not clean input on blur even when the typing is invalidate | 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 | {} | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| suffixIcon | The custom suffix icon | ReactNode | - | |
| superNextIcon | The custom super next icon | ReactNode | - | 4.17.0 |
| superPrevIcon | The custom super prev icon | ReactNode | - | 4.17.0 |
| variant | Variants of picker | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 \| `underlined`: 5.24.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) | - | |
### 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 | - | |
| 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 | - | |
| 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 | - | |
| 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 | - | |
| 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 |
| --- | --- | --- | --- | --- |
| 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/) | - | 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/) | - | 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))\[] }\[] | - | |
| renderExtraFooter | Render extra footer in panel | () => React.ReactNode | - | |
| separator | Set separator between inputs | React.ReactNode | `` | |
| 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(), 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(), 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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
);
};
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 } 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) => {
if (info.props.size === 'large') {
return {
root: {
borderRadius: 8,
border: '1px solid #CDC1FF',
},
label: { color: '#A294F9' },
} satisfies DescriptionsProps['styles'];
}
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 |
| --- | --- | --- | --- | --- |
| 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> | - | |
| 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 | CSSProperties, Please use `styles.label` instead | - | 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> | - | |
| 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
LinkLink
>
);
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.
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 |
| --- | --- | --- | --- | --- |
| children | The wrapped title | ReactNode | - | |
| className | The className of container | 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> | - | |
| 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 | true | 4.2.0 |
| style | The style object of container | 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> | - | |
| 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 (
<>
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 (
<>
toprightbottomleft
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,
}))}
/>
>
);
};
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 (
<>
Loading Drawer}
placement="right"
open={open}
loading={loading}
onClose={() => setOpen(false)}
>
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 (
<>
toprightbottomleft
}
>
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
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: right;
background: #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
}
>
>
);
};
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) => (
))}
);
};
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 (
<>
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 } 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: DrawerProps['styles'] = {
mask: {
backgroundImage: `linear-gradient(to top, #18181b 0, rgba(21, 21, 22, 0.2) 100%)`,
},
};
const stylesFn: DrawerProps['styles'] = (info) => {
if (info.props.footer) {
return {
header: {
padding: 16,
},
body: {
padding: 16,
},
footer: {
padding: '16px 10px',
backgroundColor: '#fafafa',
},
} satisfies DrawerProps['styles'];
}
return {};
};
const App: React.FC = () => {
const [drawerOpen, setDrawerOpen] = useState(false);
const [drawerFnOpen, setDrawerFnOpen] = useState(false);
const sharedProps: DrawerProps = {
classNames,
size: 500,
};
const footer: React.ReactNode = (
);
return (
setDrawerOpen(false)}
>
{sharedContent}
setDrawerFnOpen(false)}
>
{sharedContent}
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Props | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| afterOpenChange | Callback after the animation ends when switching drawers | function(open) | - | |
| className | Config Drawer Panel className. Use `rootClassName` if want to config top DOM style | string | - | |
| 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> | - | |
| 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 |
| ~~destroyOnClose~~ | Whether to unmount child components on closing drawer or not | boolean | false | |
| destroyOnHidden | Whether to unmount child components on closing drawer or not | boolean | false | 5.25.0 |
| extra | Extra actions area at corner | ReactNode | - | 4.17.0 |
| footer | The footer for Drawer | ReactNode | - | |
| forceRender | Pre-render Drawer component forcibly | boolean | false | |
| focusable | Configuration for focus management in the Drawer | `{ trap?: boolean, focusTriggerAfterClose?: boolean }` | - | 6.2.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 |
| ~~maskClosable~~ | Clicking on the mask (area outside the Drawer) to close the Drawer or not | boolean | true | |
| 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 | - | |
| 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> | - | |
| 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
| Props | 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 = () => (
);
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 = () => (
);
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 = () => (
);
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 onClick: MenuProps['onClick'] = ({ key }) => {
message.info(`Click on item ${key}`);
};
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 = () => (
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 handleButtonClick = (e: React.MouseEvent) => {
message.info('Click on left button.');
console.log('click left button', e);
};
const handleMenuClick: MenuProps['onClick'] = (e) => {
message.info('Click on menu item.');
console.log('click', e);
};
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 menuProps = {
items,
onClick: handleMenuClick,
};
const App: React.FC = () => (
} />
} />
} disabled />
} iconPlacement="end">
Button
} 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 },
)}
)}
>
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 (
} />
} />
} />
} />
);
};
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;
```
### 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, 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) => {
const { props } = info;
const isClick = props.trigger?.includes('click');
if (isClick) {
return {
root: {
borderColor: '#1890ff',
borderRadius: '8px',
},
} satisfies DropdownProps['styles'];
}
return {};
};
const App: React.FC = () => {
const { styles } = useStyles();
const sharedProps: DropdownProps = {
menu: { items },
placement: 'bottomLeft',
classNames: { root: styles.root },
};
return (
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Dropdown
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| 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> | - | |
| 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> | - | |
| 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 | |
| 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
}
>
);
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 = () => (
>
);
};
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 { Button, Empty, Flex } from 'antd';
import { createStaticStyles } from 'antd-style';
import type { EmptyProps } from '..';
const emptySharedProps: EmptyProps = {
image: Empty.PRESENTED_IMAGE_SIMPLE,
children: ,
};
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 }) => {
if (props.description) {
return {
root: { backgroundColor: '#e6f7ff', border: '1px solid #91d5ff' },
description: { color: '#1890ff', fontWeight: 'bold' },
image: { filter: 'hue-rotate(180deg)' },
} satisfies EmptyProps['styles'];
}
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
```
| 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> | - | |
| description | Customize description | ReactNode | - | |
| image | Customize image. Will treat as image url when string provided | ReactNode | `Empty.PRESENTED_IMAGE_DEFAULT` | |
| imageStyle | The style of image | 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> | - | |
## 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)}>
horizontalvertical
{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 :
);
};
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' && }
);
};
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) => (
))}
);
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.”
);
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 |
| --- | --- | --- | --- | --- |
| vertical | Is direction of the flex vertical, use `flex-direction: column` | boolean | `false` | |
| 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 = () => (
);
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 } 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) => {
if (info.props.type === 'primary') {
return {
root: {
backgroundColor: '#171717',
},
content: {
color: '#fff',
},
} satisfies FloatButtonProps['styles'];
}
return {};
};
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 |
| --- | --- | --- | --- | --- |
| icon | Set the icon component of button | 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> | - | |
| 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> | - | |
| 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 |
### FloatButton.Group
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| open | Whether the menu is visible or not, use it with trigger | boolean | - | |
| closeIcon | Customize close button icon | React.ReactNode | `` | |
| 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
);
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
}
);
};
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 (
HorizontalVerticalInline
);
};
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 ({
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 (
);
};
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 (
DefaultOptionalHiddenCustomize }}
>
);
};
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 (
SmallMediumLarge
);
};
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 = () => (
);
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 [form] = Form.useForm();
const onFinish = () => {
message.success('Submit success!');
};
const onFinishFailed = () => {
message.error('Submit failed!');
};
const onFill = () => {
form.setFieldsValue({
url: 'https://taobao.com/',
});
};
return (
);
};
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 (
);
};
const App: React.FC = () => {
const [form] = Form.useForm();
return (
Submit
);
};
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}
))}
>
)}
);
};
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)} />
))}
>
)}
);
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 }) => (
)}
);
};
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 = () => (
);
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?
);
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 (
);
};
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).
**Note:** Save 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?: any;
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' }]);
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. )
);
}}
);
};
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" />
{() => (
)}
);
};
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 meForgot password
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!'));
},
}),
]}
>
value ? Promise.resolve() : Promise.reject(new Error('Should accept agreement')),
},
]}
{...tailFormItemLayout}
>
I have read the agreement
);
};
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(
>
);
};
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 (
<>
{JSON.stringify(formValues, null, 2)}
setOpen(false)}
destroyOnHidden
modalRender={(dom) => (
)}
>
PublicPrivate
>
);
};
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 = () => (
);
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
);
};
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()}`}
>
);
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 (
);
};
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 1item 2item 3item 1item 2item 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.
);
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 } 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) => {
if (info.props.variant === 'filled') {
return {
root: {
border: '1px solid #1677FF',
},
label: {
textAlign: 'end',
color: '#1677FF',
},
content: {
paddingInlineStart: 12,
},
} satisfies FormProps['styles'];
}
return {};
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
const sharedProps: FormProps = {
labelCol: { span: 4 },
wrapperCol: { span: 20 },
autoComplete: 'off',
classNames,
};
const sharedFormContent = (
<>
>
);
return (
<>
>
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
### Form
| 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> | - | |
| 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 | |
| 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` | |
| 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 |
| 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 |
| 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> | - | |
| tooltip | Config tooltip props | [TooltipProps](/components/tooltip#api) & { icon?: ReactNode } | - | 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) | - | |
| 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 |
| 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 uninstalled | 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 align of 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 ,
Submit
,
Search on Google
,
]}
>
);
};
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 = () => (
InfoSuccessErrorWarning
);
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 = () => (
ConfirmWith 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 { 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) => {
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',
},
} satisfies ModalProps['styles'];
}
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 |
| --- | --- | --- | --- | --- |
| afterClose | Specify a function that will be called when modal is closed completely | function | - | |
| cancelButtonProps | The cancel button props | [ButtonProps](/components/button/#api) | - | |
| cancelText | Text of the Cancel button | ReactNode | `Cancel` | |
| centered | Centered Modal | boolean | false | |
| 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> | - | |
| closable | Whether a close (x) button is visible on top right or not | boolean \| [ClosableType](#closabletype) | true | - |
| closeIcon | Custom close icon. 5.7.0: close button will be hidden when setting to `null` or `false` | ReactNode | <CloseOutlined /> | |
| 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 |
| 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 |
| ~~maskClosable~~ | Whether to close the modal dialog when the mask (area outside the modal) is clicked | boolean | true | |
| modalRender | Custom modal content render | (node: ReactNode) => ReactNode | - | 4.7.0 |
| okButtonProps | The ok button props | [ButtonProps](/components/button/#api) | - | |
| 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 | - | |
| 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> | - | |
| 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-cn#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}` | true | |
| maskClosable | Whether to close the modal dialog when the mask (area outside the modal) is clicked | 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 | 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. | 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;
```
### Customized style
The style and className are available to customize Notification.
```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:
'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
className: 'custom-class',
style: {
width: 600,
},
});
};
return (
<>
{contextHolder}
Open the notification box
>
);
};
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. More than 3 notifications will be automatically stacked, and could be changed by `threshold`.
```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 dom styling
You can customize the [semantic dom](#semantic-dom) style of Notification by passing objects/functions through `classNames` and `styles`.
```tsx
import React from 'react';
import { Button, notification, Space } from 'antd';
import type { NotificationArgsProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
border: 2px dashed #ccc;
`,
}));
const styleFn: NotificationArgsProps['styles'] = ({ props }) => {
if (props.type === 'error') {
return {
root: {
backgroundColor: `rgba(255, 200, 200, 0.3)`,
},
} satisfies NotificationArgsProps['styles'];
}
return {};
};
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const sharedProps: NotificationArgsProps = {
title: 'Notification Title',
description: 'This is a notification description.',
duration: false,
classNames: { root: classNames.root },
};
const openDefault = () => {
api.info({
...sharedProps,
styles: { root: { borderRadius: 8 } },
});
};
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 |
| --- | --- | --- | --- | --- |
| actions | Customized button group | ReactNode | - | 5.24.0 |
| ~~btn~~ | Customized close button group, please use `actions` instead | ReactNode | - | - |
| className | Customized CSS class | 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> | - | |
| closeIcon | Custom close icon | ReactNode | true | 5.7.0: close button will be hidden when setting to null or false |
| 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) | - | - |
| 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> | - | |
| 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 |
| --- | --- | --- | --- | --- |
| 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 |
| 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 | |
| colorBgBlur | Control the background color of frosted glass container, usually transparent. | 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 | |
| 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}
antd will dynamic create React instance by `ReactDOM.render` when call notification methods. Whose context is different with origin code located context.
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 Package 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 = () => (
SmallLarge
);
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 { 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 }) => {
if (props.size === 'small') {
return {
item: {
backgroundColor: `rgba(200, 200, 200, 0.3)`,
marginInlineEnd: 4,
},
} satisfies PaginationProps['styles'];
}
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 |
| --- | --- | --- | --- | --- |
| 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> | - | |
| 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 |
| totalBoundaryShowSizeChanger | When `total` larger than it, `showSizeChanger` will be true | number | 50 | |
| 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> | - | |
| total | Total number of data items | number | 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 | |
| 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 = () => (
TLTopTRLTLeftLBRTRightRBBLBottomBR
);
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 (
Scroll The Window
);
};
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 [open, setOpen] = useState(false);
const [condition, setCondition] = useState(true);
const changeCondition = (checked: boolean) => {
setCondition(checked);
};
const confirm = () => {
setOpen(false);
message.success('Next step.');
};
const cancel = () => {
setOpen(false);
message.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 (
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 { 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) => {
if (!info.props.arrow) {
return {
container: {
backgroundColor: 'rgba(53, 71, 125, 0.8)',
padding: 12,
borderRadius: 4,
},
title: {
color: '#fff',
},
content: {
color: '#fff',
},
} satisfies PopconfirmProps['styles'];
}
return {};
};
const App: React.FC = () => {
return (
Object StyleFunction Style
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Param | Description | Type | Default value | Version |
| --- | --- | --- | --- | --- |
| 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 | <ExclamationCircle /> | |
| 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 = (
Content
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 = (
Content
Content
);
const App: React.FC = () => (
Hover meFocus meClick 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 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 (
TLTopTRLTLeftLBRTRightRBBLBottomBR
);
};
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 (
Scroll The Window
);
};
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 { 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) => {
if (!info.props.arrow) {
return {
container: {
backgroundColor: 'rgba(53, 71, 125, 0.8)',
padding: 12,
borderRadius: 4,
},
content: {
color: '#fff',
},
} satisfies PopoverProps['styles'];
}
return {};
};
const App: React.FC = () => {
return (
Object StyleFunction Style
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| Param | Description | Type | Default value | 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> | - | |
| 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> | - | |
## 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 | |
| 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 | |
| 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 = () => (
);
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 = () => (
);
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 { GapPlacement } from '../progress';
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 { ProgressProps } from 'antd';
const classNames: ProgressProps['classNames'] = {
root: 'demo-progress-root',
rail: 'demo-progress-rail',
track: 'demo-progress-track',
};
const stylesFn: ProgressProps['styles'] = (info) => {
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,
},
} satisfies ProgressProps['styles'];
};
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 |
| --- | --- | --- | --- | --- |
| 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> | - | |
| 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> | - | |
| 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 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 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 (
);
};
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 { 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) => {
if (info.props.type === 'canvas') {
return {
root: {
border: '2px solid #ff4d4f',
borderRadius: 8,
padding: 16,
backgroundColor: 'rgba(255, 77, 79, 0.1)',
},
} satisfies QRCodeProps['styles'];
}
};
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 |
| :-- | :-- | :-- | :-- | :-- |
| 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> | - | |
| 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-cn#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> | - | |
| type | render type | `canvas \| svg` | `canvas` | 5.6.0 |
| value | scanned text | string | - | |
### 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 (
);
// No recommended 🙅🏻♀️
return (
ABC
);
```
## 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 } from 'antd';
import { Input, Radio } from 'antd';
const labelStyle: React.CSSProperties = {
height: 32,
lineHeight: '32px',
};
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 = () => (
HangzhouShanghaiBeijingChengduHangzhou
Shanghai
BeijingChengduHangzhouShanghaiBeijingChengdu
);
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 = () => (
HangzhouShanghaiBeijingChengduHangzhouShanghaiBeijingChengduHangzhouShanghaiBeijingChengdu
);
export default App;
```
### Solid radio button
Solid radio button style.
```tsx
import React from 'react';
import { Flex, Radio } from 'antd';
const App: React.FC = () => (
HangzhouShanghaiBeijingChengduHangzhou
Shanghai
BeijingChengdu
);
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 { 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) => {
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 |
| --- | --- | --- | --- | --- |
| 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 |
| 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 |
| 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 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
Support set allow to clear star when click again.
```tsx
import React from 'react';
import { Flex, Rate } from 'antd';
const App: React.FC = () => (
allowClear: trueallowClear: 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 |
| --- | --- | --- | --- | --- |
| 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 |
| className | The custom class name of rate | string | - | |
| 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' | |
| style | The custom style object of rate | CSSProperties | - | |
| 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,
]}
>
The content you submitted has the following error:
Your account has been
frozen. Thaw immediately > Your account is not yet
eligible to apply. Apply Unlock >
Action}
/>
>
);
};
export default App;
```
## API
Common props ref:[Common props](/docs/react/common-props)
| 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> | - | |
| 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> | - | |
| 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 | number | 72 |
| subtitleFontSize | Subtitle font size | number | 14 |
| titleFontSize | Title font size | 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 { SizeType } from '../../config-provider/SizeContext';
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 = () => (
),
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 { SegmentedProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
padding: 2px;
`,
}));
const styleFn: SegmentedProps['styles'] = (info) => {
if (info.props.vertical) {
return {
root: {
border: '1px solid #77BEF0',
padding: 4,
width: 100,
},
icon: {
color: '#77BEF0',
},
item: {
textAlign: 'start',
},
} satisfies SegmentedProps['styles'];
}
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`
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| 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> | - | |
| defaultValue | Default selected value | string \| number | | |
| 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> | - | |
| 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 (
<>
LargeMediumSmall