Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: AutoFocus on Input field inside Modal

I use Antd. I have Modal Window which consist Form. I want to focus in Input Field when user open the modal widnow. How i can do it in functional component? I try this but in not work for me:


const EditForm = ({visible, widget, onSave, onCancel}) => {
  const nameInput = useRef();
  useEffect(() => nameInput.current && nameInput.current.focus());
  const [form] = Form.useForm();
   return (
    <div>
      <Modal
        visible={visible}
        title='Edit'
        okText='Save'
        cancelText='Cancel'
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then(values => {
              form.resetFields();
              onSave(values);
            })
            .catch(info => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          {...formItemLayout}
          layout={formLayout}
          form={form}
        >
          <Form.Item />
          <Form.Item
            name='nameWidget'
            label='Name'
          >
            <Input name='nameWidget' ref={nameInput} onChange={handleChangeName} placeholder='Введите новое название' />
          </Form.Item>

        </Form>
      </Modal>
    </div>
  );
};
like image 987
Утка Обычная Avatar asked Aug 24 '26 04:08

Утка Обычная


2 Answers

try this way. good luck ;)

import React, {useState, useRef, useEffect}  from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Modal, Button, Input, Form } from 'antd';


const App = () => {
  const [visible, setVisible] = useState(false)
  const myRef = useRef();

  /*
   *  This is the main different
   */
  useEffect(()=>{
    if (myRef && myRef.current) {
      const { input } = myRef.current
      input.focus()
    }

  })
  const showModal = () => {
    setVisible(true)
  };

  const handleOk = e => {
    setVisible(false)
  };

  const handleCancel = e => {
    setVisible(false)
  };

  return (
    <>
      <Button type="primary" onClick={showModal}>
        Open Modal with customized button props
      </Button>
      <Modal
        title="Basic Modal"
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        okButtonProps={{ disabled: true }}
        cancelButtonProps={{ disabled: true }}
      >
        <p>Some contents...</p>
        <p>Some contents...</p>
        <p>Some contents...</p>
        <Form>
          <Form.Item>
            <Input ref={myRef} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}

ReactDOM.render(<App />, document.getElementById('container'));
like image 62
Liu Lei Avatar answered Aug 25 '26 19:08

Liu Lei


You can actually accomplish this without using any refs at all.

First, put the autoFocus prop on your Input.

<Input autoFocus name='nameWidget' ref={nameInput} onChange={handleChangeName} placeholder='Введите новое название' />

This alone will not work yet as Ant Design renders modal dialogs outside of your application's root DOM element which trips up React's handling of autoFocus. If the root element is

<div id="app"></div>

as is customary, you need to tell Ant to render the Modal into this element by using the getContainer prop:

<Modal
  getContainer={document.getElementById('app')}
  // ...
>
like image 45
lishaak Avatar answered Aug 25 '26 19:08

lishaak