Created
September 23, 2020 17:35
-
-
Save arnonate/19ec38fe2f0b491de417c4e4f36e6fe7 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
// useModal.ts | |
import React from "react"; | |
export const useModal = () => { | |
const [modalIsVisible, setModalIsVisible] = React.useState(false); | |
const toggleModalVisibility = () => setModalIsVisible(!modalIsVisible); | |
return { modalIsVisible, toggleModalVisibility }; | |
}; | |
// Modal.tsx | |
import React from "react"; | |
import ReactDOM from "react-dom"; | |
import { Book } from "../../hooks/useBooks"; | |
type ModalProps = { | |
isVisible: boolean; | |
toggleVisibility: () => void; | |
}; | |
export const Modal = ({ | |
isVisible, | |
toggleVisibility, | |
}: Readonly<ModalProps>): JSX.Element | null => { | |
const modal = ( | |
<> | |
<div className="backdrop" onClick={toggleVisibility} /> | |
<div className="modal" aria-modal aria-label="Book Details" role="dialog"> | |
// Modal Content | |
<span | |
className="modal-close" | |
aria-label="Close Book Details" | |
onClick={toggleVisibility} | |
> | |
× | |
</span> | |
</div> | |
</> | |
); | |
return isVisible ? ReactDOM.createPortal(modal, document.body) : null; | |
}; | |
// ModalConsumer.tsx | |
import React from "react"; | |
import { Modal } from "../"; | |
import { useModal } from "../../hooks/useModal"; | |
export const ModalConsumer = (): JSX.Element => { | |
const { modalIsVisible, toggleModalVisibility } = useModal(); | |
const handleModalClick = (): void => { | |
toggleModalVisibility(); | |
}; | |
return ( | |
<div className="modal-consumer"> | |
<Modal | |
isVisible={modalIsVisible} | |
toggleVisibility={toggleModalVisibility} | |
/> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment