Search code examples
reactjsantdant-design-pro

How to disable a field in Ant Design React Form?


I am using React with Ant Design and I want to disable one Form.Item username field. Please see my sample code below,

<Form.Item disabled style={{ padding: '0px 20px' }}>
    {getFieldDecorator('username', {
        initialValue: this.state.userInfo.username,
        validate: [
            {
                trigger: ['onChange', 'onBlur'],
                rules: [
                    {
                        required: true,
                        message: t('pleaseInput.username'),
                    }
                ],
            },
        ],
    })
</Form.Item>

Solution

  • You need to display some sort of UI component inside your <Form.Item>.

    I suppose you want to display an <Input> since you have a username. Here's what could be possible with your code :

    <Form.Item disabled style={{ padding: '0px 20px' }}>
        {getFieldDecorator('username', {
            initialValue: this.state.userInfo.username,
            validate: [
                {
                    trigger: ['onChange', 'onBlur'],
                    rules: [
                        {
                            required: true,
                            message: t('pleaseInput.username'),
                        }
                    ],
                },
            ],
        })(
            <Input
             // This is where you want to disable your UI control
             disabled={true}
             placeholder="Username"
            />
          )}
    </Form.Item>
    

    Edit 2021: this answer targets the use of ant design's v3 Form component. While the boolean to disable a field might be the same, the Form component in the v4 has seen a lot of changes. See the documentation to migrate from v3 to v4 here.