Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 406
Jerry Avatar asked Apr 23 '20 08:04

Jerry


People also ask

How do I disable a form in React?

Disable the TextBox by adding the e-disabled to the input parent element and set disabled attribute to the input element.

What is valuePropName?

valuePropName is the name of the prop of the child component that will contain the value. In most cases, components such as Input or Select use value as the prop for holding the value. However, certain components such as Checkbox or Switch use checked .

Is antd heavy?

antd is 348kB uncompressed. The entire app including antd, React and stupidly large lodash plus lots of other stuff is 350kB gzipped.


Video Answer


1 Answers

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.

like image 184
Clafou Avatar answered Oct 24 '22 04:10

Clafou