Search code examples
reactjsreact-bootstrap

React-Bootstrap input text lose focus when opened from a OverlayTrigger in a Modal


I have a button in a modal that on click opens a popover component, in the popover I have an input text field.

The problem I have is that the input lose focus instantly, I can't type in it because something else is hijacking the focus out of it and I can't figure out what is, here is a working example of the problem.

And here is the code in question:

import "./styles.css";

import { Fragment, useState } from "react";
import { Button, Modal, OverlayTrigger, Popover, Form } from "react-bootstrap";

export default function App() {
  const [showModal, setShowModal] = useState(false);
  const [inputValue, setInputValue] = useState("");

  const popover = (
    <Popover id="popover-basic">
      <Popover.Content>
        <Form.Control
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          placeholder="Enter value"
        />
      </Popover.Content>
    </Popover>
  );

  return (
    <div className="App">
      <Fragment>
        <Button variant="primary" onClick={() => setShowModal(true)}>
          Open
        </Button>

        {showModal && (
          <Modal
            show={showModal}
            onHide={() => setShowModal(false)}
            centered
            backdrop="static"
            animation={false}
          >
            <Modal.Header closeButton>modal</Modal.Header>
            <Modal.Body>
              <p>Hello</p>

              <OverlayTrigger
                trigger="click"
                placement="right"
                overlay={popover}
              >
                <Button variant="secondary">Open Popover</Button>
              </OverlayTrigger>
            </Modal.Body>
          </Modal>
        )}
      </Fragment>
    </div>
  );
}

Solution

  • Modal has a property "enforceFocus", which keeps focus on the Modal component. The property value is set to true per default. Set it to false and you will be able to use your input.

    "https://react-bootstrap-v4.netlify.app/components/modal/#modal-props