Search code examples
javascriptreactjsantd

Why the autofocus isn't working in ReactJS with antd?


I'm having trouble with the autoFocus, I searched a lot, but none solutions that I found worked for me, I'm using a Drawer with a form inside, that form has some Form.Item with Input, and when I open the drawer, I want to focus on form.item, anybody can help me?

Here is my code:

<Drawer>
  <Form layout="vertical" ref={this.formRef} onFinish={this.onFinish} onFinishFailed={this.onFinishFailed}>    
    <Row gutter={16}>
      <Col span={24}>
        <Form.Item
          name="description"
          label="Description"
          rules={[
            {
              required: true,
              message: 'Please enter a description.',
            },
          ]}
        >
          <Input.TextArea autoFocus rows={10} placeholder="Please enter a description." />
        </Form.Item>
      </Col>
    </Row>
    <Row style={{ bottom: '0', position: 'absolute', right: '38px' }}>
      <Form.Item>
        <Button
          onClick={this.onClose}
          style={{ marginRight: 8 }}
        >
          Cancel
      </Button>
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Row>
  </Form>
</Drawer>

Solution

  • According to the docs, autoFocus is not supported prop (like it is on <input /> element). Haven't used this ui lib before, so can't say if setting focus manually by using ref would work.

    UPDATE:

    Just have played a bit and it looks like that focus can be set manually:

    1. demo
    2. code

    Another update:

    1. demo with drawer
    2. code