언젠가 모달창을 쓸 일이 있었는데, 그냥 구글링 한 코드 그대로 복붙해서 갖다 썼던 기억이 있다. 이번에는 디자인도 제대로 입혀서 쓰고 싶어서 더 많이 찾아봤는데 대부분 라이브러리를 많이 이용하는 것 같았다.
나는 내가 맡은 구역 이외에도 다른 팀원이 가져다 쓸 수 있도록 템플릿 같은 개념의 ModalFrame을 만들어 놓고 추가적인 속성이나 안에 들어가는 컴포넌트들은 ModalFrame의 children으로 구성하도록 하고 싶었다. 또, 모달 배경을 블러 처리 해야 했고 그 배경을 눌렀을 때 모달이 닫히게 만들고 싶었기 때문에 열심히 찾아보고 만들어보고 하던 중 딱 맞는 블로그 발견. 이 분 블로그를 보고 참고해서 만들었다.

import React from 'react'; | |
import styled from 'styled-components'; | |
import close from '../../assets/close-icon.png'; | |
const Container = styled.div` | |
position: absolute; | |
width: 100%; | |
height: 100%; | |
z-index: 100; | |
top: 0; | |
left: 0; | |
right: 0; | |
bottom: 0; | |
display: flex; | |
flex-direction: column; | |
align-items: center; | |
`; | |
const Background = styled.div` | |
position: fixed; | |
width: 100%; | |
height: 100%; | |
background-color: rgba(255,255,255,0.15); | |
backdrop-filter: blur(5px); | |
animation: modal-bg-show 1s; | |
@keyframes modal-bg-show { | |
from { | |
opacity: 0; | |
} | |
to { | |
opacity: 1; | |
} | |
} | |
`; | |
const ModalBlock = styled.div` | |
position: absolute; | |
top: 6.5rem; | |
border-radius: 10px; | |
padding: 1.5rem; | |
background-color: black; | |
width: 60rem; | |
@media (max-width: 1120px) { | |
width: 50rem; | |
} | |
@media (max-width: 50rem) { | |
width: 80%; | |
} | |
min-height: 35rem; | |
animation: modal-show 1s; | |
@keyframes modal-show { | |
from { | |
opacity: 0; | |
margin-top: -50px; | |
} | |
to { | |
opacity: 1; | |
margin-top: 0; | |
} | |
} | |
`; | |
const Close = styled.img.attrs({ | |
src: close, | |
})` | |
position: absolute; | |
right: 1.5rem; | |
top: 1.5rem; | |
cursor: pointer; | |
`; | |
const Contents = styled.div` | |
display: flex; | |
flex-direction: column; | |
align-items: center; | |
`; | |
const ModalFrame = ({ _handleModal, children, ...rest }) => { | |
return ( | |
<Container> | |
<Background onClick={_handleModal} /> | |
<ModalBlock {...rest}> | |
<Close onClick={_handleModal} /> | |
<Contents> | |
{children} | |
</Contents> | |
</ModalBlock> | |
</Container> | |
); | |
}; | |
export default ModalFrame; |
_handleModal로 모달이 open/close 되는 토글 함수를 전달해 주면 되고, ...rest를 사용하여 다른 컴포넌트에서도 style, onClick 등의 props를 사용할 수 있도록 했다. 아래는 ModalFrame을 사용해서 안에 children을 넣어준 새로운 ProjectModal 컴포넌트다.
import React from 'react'; | |
import ModalFrame from '../common/ModalFrame'; | |
const ProjectModal = ({ _handleModal }) => { | |
return ( | |
<ModalFrame _handleModal={_handleModal}> | |
<h1>프로젝트 내용</h1> | |
</ModalFrame> | |
); | |
}; | |
export default ProjectModal; |
아래와 같이 내용이 잘 들어간 걸 확인할 수 있다.
react modal example / react 모달 구현 / react modal 예제 / 리액트 모달 구현 / 리액트 모달 만들기 / 리액트 modal / react modal 배경 클릭 시 닫기 / 리액트 팝업 / react 팝업 / react 모달 예제

/ 배경 블러 / css blur background / css blur / react blur / css 블러 / 리액트 배경 흐리게
'dev > react' 카테고리의 다른 글
[React] Link로 페이지 이동 시 맨 위로 스크롤 (1) | 2021.11.22 |
---|---|
[React] 프로젝트에 구글폰트 적용하기 (0) | 2021.11.11 |
[React] 모달 오픈 시 외부(배경) 스크롤 막기 (0) | 2021.11.11 |