Reputation: 173
I need to close the modal also using the "ESC" key, at the moment it is closing the "CLOSE" and "CONFIRM" button. i'm using reactstrap, react hooks. keyboard {show} and handleClose it didn't work.
Here is the code:
const DeleteUserModal = props => {
const { user, show } = props;
const deleteUser = async () => {
await props.removeUser(user);
props.onCloseModal();
};
const handleKeyPress = target => {
if (target.charCode === ENTER_KEY) {
deleteUser();
}
};
return (
<div onKeyPress={handleKeyPress}>
<Modal isOpen={show} toggle={props.onCloseModal} >
<ModalHeader toggle={props.onCloseModal}>
<IntlMessages id="modal.delete.user.title" />
</ModalHeader>
<ModalBody>
<IntlMessages id="modal.delete.user.description" />
</ModalBody>
<ModalFooter>
<Button className="cancel" onClick={props.onCloseModal}>
<IntlMessages id="modal.common.cancel" />
</Button>
<Button className="action" onClick={deleteUser}>
<IntlMessages id="modal.common.ok" />
</Button>
</ModalFooter>
</Modal>
</div>
);
};
export default DeleteUserModal;
follows the modal with two actions
Upvotes: 16
Views: 33926
Reputation: 1
Consider using the native <dialog>
HTML element so then you can have access to the onClose
prop, use it to perform any cleanup that you might want (e.g close the modal, trigger state stc...)
Upvotes: 0
Reputation: 539
Here's an example using TypeScript and the new event.key
property:
React.useEffect(() => {
const closeOnEscapePressed = (e: KeyboardEvent) => {
if (e.key === "Escape") {
props.onCloseModal();
}
};
window.addEventListener("keydown", closeOnEscapePressed);
return () =>
window.removeEventListener("keydown", closeOnEscapePressed);
}, []);
Upvotes: 2
Reputation: 524
You can setup an event listener.
useEffect(() => {
const close = (e) => {
if(e.keyCode === 27){
props.onCloseModal()
}
}
window.addEventListener('keydown', close)
return () => window.removeEventListener('keydown', close)
},[])
Upvotes: 37
Reputation: 903
In vanilla JavaScript, you could do:
document.onkeydown = function (evt) {
if (evt.keyCode == 27) {
// Escape key pressed
props.onCloseModal();
}
};
Upvotes: 3
Reputation: 841
You can check bootstrap documentation.
If nothing found, then you could add an event listener to the ESC key press and than call onCloseModal
Upvotes: 1