Ant Design provides a powerful and easy-to-use form system with a lot of components for developer to use, and it’s also
easy for developers to create a custom component to be used as a form items.

To do so, you’ll need to understand how Ant Design’s Form.Item component handles value of its child component:

  • Form.Item sets a prop called value to its child component.
  • Form.Item reads its child components value from a callback prop called onChange.

Here’s an example of Ant Design’s custom widget:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import {useState} from 'react';
import styles from './index.less';
import {Form, Button} from 'antd';

type CustomFormItemProps = {
value?: number;
onChange?: (count: number) => void
};

/**
* A demo that changes it's number value on click.
* @param value initialValue passed by parent Form.Item.
* @param onChange a callback for Form.Item to read its child component's value.
* @constructor
*/
const CustomFormItem: React.FC<CustomFormItemProps> = ({value, onChange}) => {

const [count, setCount] = useState(value || 0);

const change = (n: number) => {
const newCount = count + n;
setCount(newCount);
if (typeof onChange === 'function') {
onChange(newCount);
}
};

return <>
<a onClick={() => change(-1)}>-</a>
{count}
<a onClick={() => change(1)}>+</a>
</>;
}

const App = () => {

const onFinish = (values: { count: number }) => {
alert(JSON.stringify(values));
};

return <Form onFinish={onFinish}>
<Form.Item label={'count'} name={'count'} initialValue={0}>
<CustomFormItem/>
</Form.Item>
<Button htmlType='submit' type='primary'>submit</Button>
</Form>
}

export default App;