Skip to content

Instantly share code, notes, and snippets.

@benoitguigal
Created May 25, 2020 08:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benoitguigal/2b7a737299f3517f1393666d748a1b60 to your computer and use it in GitHub Desktop.
Save benoitguigal/2b7a737299f3517f1393666d748a1b60 to your computer and use it in GitHub Desktop.
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>
);
}
.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