reactjsautofocus

React + modal: input field auto focus


I'm using React and Ant Design.

I have a popover with a button. When the user clicks the button, it shows the modal with an input field.

Problem

When I click the Show Modal Button auto focus is not working and also popover is not hiding

I tried with HTML5 autoFocus

<textarea autoFocus></textarea>

But it did not work, here the code: stackblitz


Solution

  • When you show Modal, you can use ref of your textarea to manually set focus.

     showModal=()=> {
        this.setState({
            visible: true,
            popOverVisible: false
        },()=>{
          setTimeout(()=>{this.testInput && this.testInput.focus()}, 1);
        });
     }
    

    In Your Modal,

    <Modal ...>
      ...
      <textarea 
       type='text'
       ref={(textarea) => { this.testInput = textarea; }} ></textarea>
      ...
    </Modal>
    

    To hide you Popover, you can use visible prop of PopOver and set state accordingly.

     showPopOver = () => {
        this.setState({
          popOverVisible: true
        })
     }
     ...
     <Popover ...
       visible={this.state.popOverVisible}>
       <span type="primary" onClick={this.showPopOver}>Click me (Popover Button)</span>
     </Popover>
    

    Hope this helps.

    Working demo

    For multiple PopOvers : Demo