ProTable - Advanced Tables

ProTable was created to solve the problem of having to write a lot of sample code for tables in a project, so a lot of common logic was encapsulated in it. These wrappers can be simply categorized as pre-defined behaviors and pre-defined logic.

Thanks to ProForm's capabilities, ProForm can take many forms, switch between query form types, set up deformations to become a simple Form form, perform new creation, etc.

layout\n

When to Use

When your forms need to interact with the server or need multiple cell styles, ProTable is the right choice.

Code Demo

Querying a table

高级表格
标题
状态
标签
创建时间
操作
暂无数据

Downgrade to a normal table

表格标题
应用名称
容器数量
状态创建者
创建时间
备注操作
AppName8已上线陈帅帅2022-08-08简短备注文案
AppName18关闭陈帅帅2022-08-08
AppName9关闭曲丽丽2022-08-08简短备注文案
AppName1异常付小小2022-08-08
AppName11运行中林东东2022-08-08简短备注文案
  • 第 1-5 条/总共 5 条
  • 1

Lightweight filter replacement query form

应用名称创建者
创建时间
操作
暂无数据

Forms without ToolBar

成员名称账号手机号角色权限范围操作
巴巴
[email protected]12345678910管理员 所有权限
测试
[email protected]10923456789操作员 权限点名称1、权限点名称4
测试2
[email protected]109654446789操作员 权限点名称1
测试3
[email protected]109223346789操作员
巴巴
[email protected]12345678910操作员
  • 第 1-5 条/总共 5 条
  • 1

Nested tables

嵌套表格
应用名称状态
容器数量
创建者
创建时间
操作
AppName失败1曲丽丽2022-08-08
AppName失败17曲丽丽2022-08-08
AppName失败18陈帅帅2022-08-08
AppName失败1林东东2022-08-08
AppName未完成2曲丽丽2022-08-08
  • 第 1-5 条/总共 5 条
  • 1

Left and right structure

IPCPUMemDisk
106.14.98.10410%20%30%
106.14.98.11410%20%30%
106.14.98.12410%20%30%
106.14.98.13410%20%30%
106.14.98.14410%20%30%
106.14.98.15410%20%30%
106.14.98.16410%20%30%
106.14.98.17410%20%30%
106.14.98.18410%20%30%
106.14.98.19410%20%30%
0.0.0.0
时间点代码操作
2022-08-08 11:36:21
const getData = async params => {
          const data = await getData(params);
          return { list: data.data, ...data };
        };
2022-08-08 11:36:21
const getData = async params => {
          const data = await getData(params);
          return { list: data.data, ...data };
        };
2022-08-08 11:36:26
const getData = async params => {
          const data = await getData(params);
          return { list: data.data, ...data };
        };
  • 第 1-3 条/总共 15 条
  • 1
  • 2
  • 3
  • 4
  • 5

Batch manipulation of tables

批量操作
应用名称
容器数量
调用次数执行进度创建者
创建时间
备注操作
AppName51541
曲丽丽2022-08-08简短备注文案
AppName10300
91%
付小小2022-08-08
AppName1231
56%
付小小2022-08-08简短备注文案
AppName0506
付小小2022-08-08
AppName81207
兼某某2022-08-08简短备注文案
  • 第 1-5 条/总共 5 条
  • 1

Manipulating query forms with formRef

表单赋值
标题创建时间
暂无数据

RTL (النسخة العربية)

RTL means right-to-left.

نموذج احترافي
العنوان
الحالة
التسميةتاريخ الإنشاءالتشغيل
لا توجد بيانات

Controlled table settings columns

You can hide some columns by default, but in the action column you can select

受控模式
状态
创建时间更新时间操作
暂无数据

Tables polling network data

上次更新时间:11:36:30
序号
状态
进度更新时间创建时间
暂无数据

Search form customization

When the built-in form items don't meet our basic needs, we need to customize the default components, which we can use with fieldProps and renderFormItem.

fieldProps can pass the props through and set the select style and multi-select issues.

renderFormItem does the rewriting logic, passing in item and props for rendering, but note that we have to assign value and onChange to the props, otherwise the form won't get the parameters.

renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, . .rest }, form) => {
if (type === 'form') {
return null;
}
const status = form.getFieldValue('state');
if (status ! == 'open') {
return <Input {... .fieldProps} placeholder="Please enter test" />;
}
return defaultRender(_);
};

The definition of renderFormItem, the exact value of which can be seen by opening the console.

renderFormItem?: (
item: ProColumns<T>,
config: {
value?: any;
onChange?: (value: any) => void;
onSelect?: (value: any) => void;
type: ProTableTypes;
defaultRender: (newItem: ProColumns<any>) => JSX.Element | null;
},
form: FormInstance,
) => JSX.Element | false | null;
动态自定义搜索栏
序号标题状态
暂无数据

Form action customization

查询 Table
indexTitleMoneyCreated Time
暂无数据

Toolbar Customization

Configure toolbar rendering using the toolbar property extension.

响应日期
应用名称创建者
状态
容器数量
创建时间
操作
暂无数据

Required Inquiry Form

Try to use initialValue to solve the problem, required fields are more frustrating

高级表格
标题
状态
标签创建时间
暂无数据
高级表格
标题
状态
标签创建时间
暂无数据

Form body customization

Row0
CreatedLili Qu
Association421421
Creation Time2017-01-10
Effective Time2017-10-10
自定义表格主体
序号更新时间执行进度
暂无数据

ProTable has built-in support for internationalization, and as a component with a relatively small amount of text, we can implement internationalization ourselves at a low cost.

Here is the full amount of text

const enLocale = {
tableForm: {
search: 'Query',
reset: 'Reset',
submit: 'Submit',
collapsed: 'Expand',
expand: 'Collapse',
inputPlaceholder: 'Please enter',
selectPlaceholder: 'Please select',
},
alert: {
clear: 'Clear',
},
tableToolBar: {
leftPin: 'Pin to left',
rightPin: 'Pin to right',
noPin: 'Unpinned',
leftFixedTitle: 'Fixed the left',
rightFixedTitle: 'Fixed the right',
noFixedTitle: 'Not Fixed',
reset: 'Reset',
columnDisplay: 'Column Display',
columnSetting: 'Settings',
fullScreen: 'Full Screen',
exitFullScreen: 'Exit Full Screen',
reload: 'Refresh',
density: 'Density',
densityDefault: 'Default',
densityLarger: 'Larger',
densityMiddle: 'Middle',
densitySmall: 'Compact',
},
};
// Generate the intl object
const enUSIntl = createIntl('en_US', enUS);
import { ConfigProvider } from '@ant-design/pro-provide';
// use
<ConfigProvider
value={{
intl: enUSIntl,
}}
>
<ProTable />
</ConfigProvider>;
Basic Table
zhCNIntl
indexTitleMoneyCreated Time
暂无数据

Value type examples

valueType - Date class

日期类
创建时间日期区间时间区间更新时间更新时间关闭时间操作
暂无数据

valueType - numeric class

数字类
进度金额数字数字百分比操作
暂无数据

valueType - Style Classes

样式类
序号border 序号代码头像图片操作
暂无数据

valueType - Selection Classes

样式类
状态单选状态单选按钮状态多选状态级联选择器树形下拉框操作
暂无数据

API

ProTable puts a layer of wrapping on top of antd's Table, supports some presets, and encapsulates some behaviors. Only api's that differ from antd Table are listed here.

request

request is the most important API of ProTable, request takes an object. The object must have data and success in it, and total is also required if manual paging is needed. request takes over the loading settings and re-executes them when the query form is queried and the params parameters are modified. Also the query form values and params parameters are brought in. The following is an example.

<ProTable<DataType, Params>
// params is a parameter that needs to be self-contained
// This parameter has higher priority and will override the parameters of the query form
params={params}
request={async (
// The first parameter params is the combination of the query form and params parameters
// The first parameter will always have pageSize and current, which are antd specifications
params: T & {
pageSize: number;
current: number;
},
sort,
filter,
) => {
// Here you need to return a Promise, and you can transform the data before returning it
// If you need to transform the parameters you can change them here
const msg = await myQuery({
page: params.current,
pageSize: params.pageSize,
});
return {
data: msg.result,
// Please return true for success.
// otherwise the table will stop parsing the data, even if there is data
success: boolean,
// not passed will use the length of the data, if it is paged you must pass
total: number,
};
}}
/>

ProTable

PropertyDescriptionTypeDefault Value
requestHow to get dataSource(params?: {pageSize,current},sort,filter) => {data,success,total}-
paramsAdditional parameters used for request query, once changed will trigger reloadingobject-
postDataProcess the data obtained through request(data: T[]) => T[]-
defaultDataDefault dataT[]-
dataSourceTable data, protable recommends using request to loadT[]-
onDataSourceChangeTriggered when Table data changes(dataSource: T[]) => void-
actionRefReference to Table action for custom triggeringMutableRefObject<ActionType>-
formRefThe form instance of the query form can be obtained for some flexible configurationMutableRefObject<FormInstance>-
toolBarRenderRender toolbar, support returning a dom array, will automatically increase margin-right(action) => ReactNode[]-
onLoadTriggered after the data is loaded, it will be triggered multiple times(dataSource: T[]) => void-
onLoadingChangeTriggered when loading is modified, usually caused by network requests(loading:boolean)=>void-
onRequestErrorTriggered when data loading fails(error) => void-
tableClassNameclassName of the encapsulated tablestring-
tableStylestyle of the encapsulated tableCSSProperties-
optionstable toolbar, not displayed when set to false{{ fullScreen: boolean | function, reload: boolean | function,setting: true, density?: boolean }}{ fullScreen: false, reload :true, setting: true}
searchWhether to display the search form, when the object is passed in, it is the configuration of the search formfalse | SearchConfig-
dateFormatterConvert moment format data to a specific type, false will not be converted"string" | "number" | ((value: Moment, valueType: string) => string | number) |false"string"
defaultSizeDefault sizeSizeType-
beforeSearchSubmitMake some changes before searching(params:T)=>T-
onSizeChangeThe table size has changed(size:'default' |'middle' |'small') => void-
typepro-table type"form"-
formantd form configurationFormProps-
onSubmitTriggered when the form is submitted(params: U) => void-
onResetTriggered when the form is reset() => void-
columnEmptyTextDisplay when it is empty, display - when it is not set, false can turn off this functionstring | falsefalse
tableRenderCustom rendering table function(props,dom,domList:{ toolbar,alert,table}) => ReactNode-
toolbarTransparent transmission of ListToolBar configuration itemsListToolBarProps-
tableExtraRenderThe main function of the custom table(props: ProTableProps<T, U>, dataSource: T[]) => ReactNode;-
manualRequestDo you need to manually trigger the first request? When configured as true, the search form cannot be hiddenbooleanfalse
editableRelated configuration of editable table[TableRowEditable](/components/editable-table#editable-Editable row configuration)-
cardBorderedBorder of Card components around Table and Searchboolean | {search?: boolean, table?: boolean}false
debounceTimeDebounce timenumber10
revalidateOnFocusAutomatically re-request when the window is focusedbooleanfalse
columnsStateColumn Status Control, you can operate the display hideColumnsStateType-

RecordCreator

PropertyDescriptionTypeDefault Value
recordThe row data to be added, generally contains a unique keyT{}
positionWhere does the line increase, start or endtop | bottombottom
(...buttonProps)ButtonProps of antdButtonProps

ColumnStateType

PropertyDescriptionTypeDefault
defaultValueThe default value of the column status, only for the first timeRecord <string, ColumnsState>;
valueColumn status, support controlled modeRecord <string, ColumnsState>;
onChangeColumn status After changing(value: Record <string, ColumnsState>) => void
PersistenceKeyThe key of the persistence column is used to determine if it is the same tablestring | Number
PersistenceTypeThe type of persistence column, localStorage is also existing after closing the browser, sessionStorage closes the browser will be lostlocalstorage | sessionStorage

Search Search form

PropertyDescriptionTypeDefault Value
filterTypeFilter form type'query' | 'light''query'
searchTextSearch button textstringSearch
resetTextreset button textstringreset
submitTextThe text of the submit buttonstringSubmit
labelWidthLabel width'number' | 'auto'80
spanConfigure the number of columns in the query form'number' | 'ColConfig'defaultColConfig
classNameEncapsulated search Form classNamestring-
collapseRenderCollapse button render(collapsed: boolean,showCollapseButton?: boolean,) => ReactNode-
defaultCollapsedWhether to collapse by defaultbooleantrue
collapsedcollapsedboolean-
onCollapseCollapse button event(collapsed: boolean) => void;-
optionRenderCustom action bar((searchConfig,formProps,dom) => ReactNode[])|false-

ColConfig

const defaultColConfig = {
xs: 24,
sm: 24,
md: 12,
lg: 12,
xl: 8,
xxl: 6,
};
export type OptionsType =
| ((e: React.MouseEvent<HTMLSpanElement>, action?: ActionType) => void)
| boolean;
export type OptionConfig = {
density?: boolean;
fullScreen?: OptionsType;
reload?: OptionsType;
setting?: boolean;
search?: (SearchProps & { name?: string }) | boolean;
};

ActionRef manually triggered

Sometimes we need to manually trigger the reload of the table and other operations, we can use actionRef, the editable table also provides some operations to help us achieve our requirements faster.

interface ActionType {
reload: (resetPageIndex?: boolean) => void;
reloadAndRest: () => void;
reset: () => void;
clearSelected?: () => void;
startEditable: (rowKey: Key) => boolean;
cancelEditable: (rowKey: Key) => boolean;
}
const ref = useRef<ActionType>();
<ProTable actionRef={ref} />;
// refresh
ref.current.reload();
// Refresh and clear, the page number will also be reset, excluding the form
ref.current.reloadAndRest();
// Reset to default values, including forms
ref.current.reset();
// Clear the selected item
ref.current.clearSelected();
// start editing
ref.current.startEditable(rowKey);
// end editing
ref.current.cancelEditable(rowKey);

Columns column definition

Requesting remote data is more complicated, please see here for details.

PropertyDescriptionTypeDefault Value
titleBasically the same as in antd, but supports passing in a methodReactNode | ((config: ProColumnType<T>, type: ProTableTypes) => ReactNode)-
tooltipAn icon will be displayed after the title, and some information will be prompted after hoverstring-
ellipsisWhether to abbreviate automaticallyboolean-
copyableWhether to support copyingboolean-
valueEnumThe value enumeration will automatically convert the value as a key to retrieve the content to be displayedvalueEnum-
valueTypeThe type of value, which will generate different renderersvalueTypetext
orderThe weight in the query form, the weight is ranked firstnumber-
fieldPropsThe props of the query form will be transparently transmitted to the form item. If it is rendered as Input, all props of input are supported. Similarly, if it is select, all props of select are also supported. Also supports method input(form,config)=>Record | Record-
formItemPropsThe configuration passed to Form.Item can be configured with rules, but the default query form rules does not take effect. Need to configure ignoreRules(form,config)=>formItemProps | formItemProps-
renderTextRender like table, but must return string. If you just want to convert enumeration, you can use valueEnum(text: any,record: T,index: number,action: UseFetchDataAction<T> ) => string-
renderRender similar to table, the first parameter becomes dom, and the fourth parameter action is added(text: ReactNode,record: T,index: number,action: UseFetchDataAction<T>) => ReactNode | ReactNode[]-
renderFormItemRender the input components of the query form(item,{ type, defaultRender, formItemProps, fieldProps, ...rest },form) => ReactNode-
searchConfiguration column search related, false is hiddenfalse | { transform: (value: any) => any }true
search.transformThe key of the conversion value, generally used for the conversion of the event interval(value: any) => any-
editableWhether it is editable in the edit table, the parameters of the function are the same as the render of the tablefalse | (text: any, record: T,index: number) => booleantrue
colSizeThe number of grids occupied by a form item, proportion = colSize*span, colSize defaults to 1, span is 8, span is form={{span:8}} global setting Ofnumber-
hideInSearchDo not show this item in the query formboolean-
hideInTableDo not show this column in Tableboolean-
hideInFormDo not show this column in Formboolean-
hideInDescriptionsDo not show this column in Descriptionsboolean-
filtersThe filter menu item in the header. When the value is true, valueEnum is automatically generatedboolean | object[]false
onFilterFilter the form, use the built-in ProTable when it is true, turn off local filtering when it is false(value, record) => boolean |falsefalse
requestRequest enumeration from serverrequest-
initialValueInitial value of query form itemany-

valueType value type

ProTable encapsulates some commonly used value types to reduce repeated render operations. Configure a valueType to display formatted response data.

Batch operation

Like antd, batch operations need to be set to "rowSelection" to enable. Unlike antd, pro-table provides an alert to carry some information. You can customize it with tableAlertRender and tableAlertOptionRender. Set or return false to close.

PropertyDescriptionTypeDefault Value
alwaysShowAlertAlways show alert, no choice not to show by defaultboolean-
tableAlertRenderCustomize the information area on the left side of the batch operation toolbar, not displayed when false({ selectedRowKeys: Key[], selectedRows: T[], onCleanSelected: ()=>void }) => ReactNode)| false-
tableAlertOptionRenderCustomize the option area on the right side of the bulk operation toolbar, not displayed when false({ selectedRowKeys: Key[], selectedRows: T[], onCleanSelected: ()=>void }) => ReactNode)| false-

Searching for forms

ProTable will generate a Form for filtering list data based on columns, and the final value will be returned based on the first parameter via request, which looks like.

<ProTable request={(params,sort,filter)=>{ all params}}>

As per the specification, table forms do not require any mandatory parameters, and all clicks on search and reset will trigger a request to initiate a query.

Form's columns are generated with different types based on valueType.

Columns with a valueType of index indexBorder option and no dataIndex and key will be ignored.

ListToolbar

Toolbar section for customizing forms.

Code Demo

这里是标题
这里是子标题
响应日期
应用名称
容器数量
创建者操作
AppName7付小小
AppName10付小小
AppName19陈帅帅
AppName14曲丽丽
AppName5林东东
  • 第 1-5 条/总共 5 条
  • 1
响应日期
应用名称
容器数量
创建者操作
AppName19林东东
AppName15陈帅帅
AppName17曲丽丽
AppName9兼某某
AppName13陈帅帅
  • 第 1-5 条/总共 5 条
  • 1
无标题

列表工具栏-没有标题的情况下搜索框会前置。

两行的情况
响应日期
应用名称
容器数量
创建者操作
AppName13陈帅帅
AppName10曲丽丽
AppName0陈帅帅
AppName9曲丽丽
AppName1曲丽丽
  • 第 1-5 条/总共 5 条
  • 1
双行布局

列表工具栏-双行的情况下会有双行的布局形式。

标签
响应日期
名称状态
容器数量
创建人操作
AppName成功8兼某某
AppName成功1林东东
AppName成功17林东东
AppName成功18付小小
AppName成功1林东东
  • 第 1-5 条/总共 5 条
  • 1
带标签

列表工具栏-标签需配合 multipleLinetrue 时使用。

全部事项
响应日期
应用名称
容器数量
创建者操作
AppName18陈帅帅
AppName15付小小
AppName17兼某某
AppName18陈帅帅
AppName5曲丽丽
  • 第 1-5 条/总共 5 条
  • 1

ListToolBarProps

Toolbar configuration properties for lists and tables

ParametersDescriptionTypeDefault
titletitleReactNode-
subTitlesubTitleReactNode-
descriptiondescriptionReactNode-
searchquery areaReactNode | SearchProps-
actionsactions areaReactNode[]-
settingssettings area(ReactNode | Setting)[]-
filterThe filter area, usually used with LightFilterReactNode-
multipleLineWhether to display multiple linesbooleanfalse
menumenu configurationListToolBarMenu-
tabsTabs configuration, only valid if multipleLine is trueListToolBarTabs-

SearchProps is a property of antd's Input.Search.

Setting

ParametersDescriptionTypeDefault
iconiconReactNode-
tooltiptooltip Descriptionstring-
keyoperation unique identifierstring-
onClickset to be triggered(key: string)=>void-

ListToolBarMenu

parametersdescriptiontypedefault
typetypeinline | dropdown | tabdropdown
activeKeycurrent valuestring-
itemsmenu items{ key: string; label: ReactNode }[]-
onChangeCallback for switching menus(activeKey)=>void-

ListToolBarTabs

parametersdescriptiontypedefault
activeKeycurrently selected itemstring-
itemsmenu items{ key: string; tab: ReactNode }[]-
onChangeCallback for toggling menu items(activeKey)=>void-