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
您可以使用useRef
这里提到: useRef文档
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
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" />;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.