0

I am using react-bootstrap and importing component modal when I click on the modal button, the modal pops up but I want the focus to directly go to the input field inside the modal when open modal button is clicked, which I am not able to achieve

I have tried putting attribute as autoFocus and also tried to use refs but did not succeed as of now.

The child component

 <Modal

    aria-labelledby="contained-modal-title-vcenter"
    centered
  >

    <Modal.Body>
      <h4>File Name</h4>
      <input autoFocus aria-label="File name entering field"  className="form-control mt-3" name="term" type="text"  />
    </Modal.Body>

  </Modal>

the parent that triggers the child

 <Button 
          variant="dark"
          onClick={() => {this.setState({ modalShow: true }); } }
        >
        popper
        </Button>

        <MyVerticallyCenteredModal
          show={this.state.modalShow}
          onHide={modalClose}
          saver= {this.saveDataImage}
        />

I want the focus to directly go to the input field in the modal to have good accessibility

Harry
  • 389
  • 1
  • 6
  • 18
  • please check your answer here `https://stackoverflow.com/questions/28889826/set-focus-on-input-after-render` – Dhiren Apr 23 '19 at 04:44

3 Answers3

0

You can use useRef as mentioned here: useRef docs

Pho Huynh
  • 1,497
  • 3
  • 13
  • 23
0

in your INPUT component that you want to focus, you should add the property "autoFocus" for example:

<input autoFocus id=... name=.../>

for more information check: Set focus on input after render

Hugo Nugra
  • 21
  • 2
0

We can create a ref to our input element and when the component that mounts the input element mounts, we can use the componentDidMount lifecycle hook to focus our input.

class Input extends React.Component {
  constructor() {
    super();
    this.inputRef = React.createRef();
  }

  componentDidMount = () => {
    this.inputRef.current.focus();
  };

  render() {
    return <input ref={this.inputRef} type="text" />;
  }
}
Asaf Aviv
  • 11,279
  • 1
  • 28
  • 45
  • Thanks Asaf, I tried this but it gives me an error , TypeError: Cannot read property 'focus' of null – Harry Apr 23 '19 at 05:26
  • @Harry If you can make a simple example on [CodeSandBox](https://codesandbox.io/s/new) with just the components that triggers the `Modal` i will happily take a look at it – Asaf Aviv Apr 23 '19 at 05:29
  • I tired making a simple example but it's giving me a cross origin error and I am getting stuck. Thanks for your help anyway Asaf – Harry Apr 23 '19 at 05:47