How to Autofocus to Form Input Inside a reactstrap Modal


We need to use some fancy tricks to trigger autoFocus for our form inputs and buttons rendered inside a reactstrap modal.

Suppose we have this modal below:

<Modal>
  <Form>
    <ModalHeader>Type Your Input</ModalHeader>
    <ModalBody>
      <Input />
      <Button>Submit</Button>
    </ModalBody>
  </Form>
</Modal>

Generally, we should be able to place the autoFocus property on an input for the browser to force focus to that input on load.

The tricky thing here is that the reactstrap modal has its own focus management, and it’s given the autoFocus property when initialized.

As a result, we need to set autoFocus={false} inside the <Modal> element to opt-out of the default focus management. We then need to place autoFocus={true} to the element we want to focus on inside the modal.

<Modal autoFocus={false}>
  <Form>
    <ModalHeader>Type Your Input</ModalHeader>
    <ModalBody>
      <Input autoFocus={true} />
      <Button>Submit</Button>
    </ModalBody>
  </Form>
</Modal>