Created
May 25, 2020 08:07
-
-
Save benoitguigal/2b7a737299f3517f1393666d748a1b60 to your computer and use it in GitHub Desktop.
This file contains 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, { useRef, useEffect, ReactNode } from "react"; | |
import styles from "./Modal.module.scss"; | |
type Props = { | |
display: boolean; | |
close: () => void; | |
children: ReactNode; | |
}; | |
/** | |
* Modal component | |
*/ | |
export default function Modal({ display, close, children }: Props) { | |
const displayStyle = { | |
...(!display ? { display: "none" } : {}), | |
}; | |
const ref = useRef<HTMLDivElement>(null); | |
useEffect(() => { | |
/** | |
* Close Modal if clicked outside | |
*/ | |
function handleClickOutside(event) { | |
if (ref.current && !ref.current.contains(event.target)) { | |
close(); | |
} | |
} | |
// Bind the event listener | |
document.addEventListener("mousedown", handleClickOutside); | |
return () => { | |
// Unbind the event listener on clean up | |
document.removeEventListener("mousedown", handleClickOutside); | |
}; | |
}, [ref]); | |
return ( | |
<div className={styles.modal} style={displayStyle}> | |
<div ref={ref} className={styles.modal__content}> | |
{children} | |
</div> | |
</div> | |
); | |
} |
This file contains 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
.modal { | |
position: fixed; /* Stay in place */ | |
z-index: 1; /* Sit on top */ | |
left: 0; | |
top: 0; | |
width: 100%; /* Full width */ | |
height: 100%; /* Full height */ | |
overflow: auto; /* Enable scroll if needed */ | |
background-color: rgb(0, 0, 0); /* Fallback color */ | |
background-color: rgba(0, 0, 0, 0.4); /* Black w/ opacity */ | |
} | |
.modal__content { | |
background-color: #fefefe; | |
margin: 15% auto; /* 15% from the top and centered */ | |
padding: 20px; | |
border: 1px solid #888; | |
width: 80%; /* Could be more or less, depending on screen size */ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment