Created
July 11, 2022 19:32
-
-
Save nesbtesh/76eaa63e638901e9b1326cb438f4f906 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { CSSTransition } from "react-transition-group"; | |
import ModalPortal from "../ModalPortal"; | |
export function useModal() { | |
const [isModalVisible, setIsModalVisitble] = React.useState(false); | |
const toggleModal = () => { | |
setIsModalVisitble((prevState) => !prevState); | |
}; | |
const closeModal = () => { | |
setIsModalVisitble(false); | |
}; | |
return { isModalVisible, toggleModal, closeModal }; | |
} | |
function ModalWrapper({ children, isVisible, closeModal }) { | |
const onKeyDown = (event) => { | |
if (event.keyCode === 27) { | |
if (closeModal) closeModal(); | |
} | |
}; | |
React.useEffect(() => { | |
document.addEventListener("keydown", onKeyDown, false); | |
return () => { | |
document.removeEventListener("keydown", onKeyDown, false); | |
}; | |
}, []); | |
return ( | |
<ModalPortal> | |
<CSSTransition | |
in={isVisible} | |
timeout={200} | |
classNames="modal-transition" | |
unmountOnExit | |
> | |
{children} | |
</CSSTransition> | |
</ModalPortal> | |
); | |
} | |
export default ModalWrapper; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment