avatar

ShīnChvën ✨

Effective Accelerationism

Powered by Druid

Create A Custom Ant Design Form Item Component

Sat Jun 05 2021

Ant Design offers a robust and user-friendly form system, packed with an array of components for developers to utilize. Moreover, it allows developers to effortlessly create custom components that can be integrated as form items.

To create a custom component in Ant Design, it's essential to grasp how the Form.Item component manages the value of its child component:

  1. Form.Item assigns a value prop to its child component.
  2. Form.Item retrieves the value from its child component through a callback prop named onChange.

Below is an illustrative example of how to create a custom widget in Ant Design:

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;