카테고리 없음

[react] useModal hook 으로 모달 만들기(공통 컴포넌트)

동기는 2024. 3. 22. 09:48

 

저번 시간에 customModal 로  여러가지 커스텀 할 수 있는 모달을 만들었었는데..

그 모달을 필요한곳에 여러개 만들게 되면 계속 상태값과 모달을 열고 닫는 함수가 점점 늘어나서 가독형부분에서

떨어지는 것 같아서.. 여러군데에 계속 한다면 차라리 hook 으로 만드는게 낫겠다 싶어서

hook으로 만들기로 결심했다.

 

hook 으로 만들기 위해서는 일단 3개의 파일이 필요하다.

 

1.원천 modal component 

2.hook으로 만들어서 공용컴포넌트로 내보낼 useModal

3.그리고 이 hook 을 만들어서 보여줄 page 화면

 

 

1.진짜 모달 컴포넌트

 

import React from 'react'
import styled from '@emotion/styled'
interface ModalProps {
    onClose: any
    children: React.ReactNode
    width?: string
    height?: string
    title?: string
}

interface ModalStyleProps {
    width?: string
    height?: string
    title?: string
}
export const Modal = ({
    onClose,
    children,
    width,
    height,
    title,
}: ModalProps) => {
    return (
        <ModalWrapStyle onClick={onClose}>
            <ModalStyle
                onClick={(e: React.MouseEvent<HTMLDivElement>) =>
                    e.stopPropagation()
                }
                width={width}
                height={height}
                title={title}
            >
                {children}
            </ModalStyle>
        </ModalWrapStyle>
    )
}

const ModalWrapStyle = styled.div`
    width: 100%;
    height: 100vh;
    overflow: hidden;
    position: fixed;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.3);
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
`

const ModalStyle = styled.div<ModalStyleProps>`
    width: ${(props) => (props.width ? props.width : 2000)}px;
    height: ${(props) => (props.height ? props.height : 2000)}px;
    padding: 20px;
    background-color: #fff;
`
export default Modal