xonecas.io
366
Hc

hirenimble-challenge / files

hirenimble-challenge / src / ui-kit / BaseModal.jsx

1.5 KB
1import React, { useEffect } from 'react';
2import ReactDOM from 'react-dom';
3import styled, { keyframes } from 'styled-components';
4import { disableBodyScroll, enableBodyScroll } from 'body-scroll-lock';
5
6const portalRoot = document.getElementById('portal-root');
7
8export const BaseModal = ({ children }) => {
9  const modalRoot = React.useRef(null);
10  const modalRef = React.useRef(null);
11
12  if (modalRoot.current === null) {
13    modalRoot.current = document.createElement('div');
14    modalRoot.current.style.display = 'contents';
15  }
16
17  useEffect(() => {
18    const modalEl = modalRef.current;
19
20    portalRoot.appendChild(modalRoot.current);
21    disableBodyScroll(modalEl);
22
23    return () => {
24      enableBodyScroll(modalEl);
25      modalRoot.current.remove();
26    };
27  }, []);
28
29  return (
30    modalRoot.current &&
31    ReactDOM.createPortal(
32      <>
33        <Overlay />
34        <Container ref={modalRef}>{children}</Container>
35      </>,
36      modalRoot.current
37    )
38  );
39};
40
41const Overlay = styled.div`
42  z-index: 100;
43
44  position: fixed;
45  top: 0;
46  left: 0;
47  width: 100%;
48  height: 100vh;
49
50  background-color: rgba(0, 0, 0, 0.5);
51`;
52
53const fadeIn = keyframes`
54  0% {
55    opacity: 0;
56  }
57  100% {
58    opacity: 1;
59  }
60`;
61
62const Container = styled.div`
63  z-index: 101;
64
65  position: fixed;
66  left: 50%;
67  top: 20%;
68  transform: translate(-50%, -20%);
69
70  background-color: #ffffff;
71
72  width: 850px;
73  border-radius: 3px;
74
75  @media screen and (max-width: 850px) {
76    top: 40%;
77    transform: translate(-50%, -40%);
78    max-width: 95vw;
79  }
80
81  animation: ${fadeIn} 300ms ease-in-out;
82`;