Skip to content

Instantly share code, notes, and snippets.

@nesbtesh
Created July 11, 2022 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nesbtesh/76eaa63e638901e9b1326cb438f4f906 to your computer and use it in GitHub Desktop.
Save nesbtesh/76eaa63e638901e9b1326cb438f4f906 to your computer and use it in GitHub Desktop.
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