'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 1:[1]
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.
For multiple PopOvers : Demo
Solution 2:[2]
Add autoFocus={false} to your modal to reject the modal's focus management.
<Modal ... autoFocus={false}>
<textarea autoFocus={true}>
Solution 3:[3]
What worked for me is setting input's focus after the modal finishes transitioning in.
Using useRef hook, my code was like
...
<Modal ... onEntered={() => textarea.current.focus()} >
<textarea ... ref={textarea} />
</Modal>
Link to Modal API https://react-bootstrap.github.io/components/modal/#modal-props
Solution 4:[4]
Just add autoFocus = {false} on modal and autoFocus = {true} on input.
<Modal autoFocus={false}>
<Form>
<ModalHeader>Type Your Input</ModalHeader>
<ModalBody>
<Input autoFocus={true} />
<Button>Submit</Button>
</ModalBody>
</Form>
</Modal>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Rosy Shrestha |
| Solution 3 | |
| Solution 4 |
