🛠️ Error

[Error] SweetAlert2 가장 최상단에 위치하는 방법 (z-index)

개란나니 2024. 7. 1. 12:04

현재 React.js 기능 중 타이머 버튼을 눌렀을 때 새로 타이머가 갱신되면서 알림을 띄워주는 구조가 있다.

 

기본 라이브러리를 MUI(Material UI)를 활용해서 개발하고 있고, 알람을 SweetAlert2를 활용하려고 하였다.

기본 구조

먼저 부모 컴포넌트에서 버튼을 눌렀을 때 refreshSend 클릭이벤트가 발생하고 showAlert가 true일 시 컴포넌트가 발생하도록 한다. 

// Parents.jsx
<>
    <Button key={'Timer'} onClick={refreshSend} >
        <AccessTimeIcon/>
        <div>{timeString}</div>
    </Button>
    {showAlert && (
        <Child
            title={alertProps.title}
            text={alertProps.text}
            icon={alertProps.icon}
            onClose={handleAlertClose}
        />
    )}
</>

자식 컴포넌트에서 SweetAlert2 를 활용한 알람이 발생되도록 설정했다.

// Child.jsx
import React, {useEffect} from 'react';
import Swal from 'sweetalert2';
import "./toastAlert.scss";

const Child = ({ title, text, icon, onClose }) => {
    useEffect(() => {
        Swal.fire({
            title: title,
            text: text,
            icon: icon,
        }).then((result) => {
            // Swal이 닫힌 후 실행할 코드
            if (onClose) {
                onClose();
            }
        });
    }, [title, text, icon, onClose]);
    return null;
};

export default Child;

 

문제 발생

기본 페이지에서는 해당 Alert가 잘 발생되고 보여지는데,

MUI Drawer를 사용한 다른 페이지가 보여질 때 사용하면 Drawer 컴포넌트에 가져져서 해당 Alert가 보여지지 않는다.

 

문제 원인

문제는 MUI의 Drawer 컴포넌트와 SweeAlert2 팝업이 겹칠 때 발생하는 'z-index' 문제라고 생각했다.

MUI의 Drawer가 기본적으로 높은 'z-index'를 가지고 있고, SweetAlert2의 팝업이 Drawer의 'z-index' 보다 낮기 때문에 팝업이 Drawer 뒤에 숨겨질 수 있었다.

 

문제 해결

따라서 'z-index'를 사용하여 Drawer컴포넌트 보다도 Alert를 높게 설정하여 가장 최상단으로 올리면 되지 않을 까 생각했다. 

(MUI Drawer의 기본 z-index는 1200 이고, 따라서 SweetAlert2의 z-index를 1300 이상으로 설정하면 Drawer 보다 앞에 오게된다.)

 

const Child = ({ title, text, icon, onClose }) => {
    useEffect(() => {
        Swal.fire({
            title: title,
            text: text,
            icon: icon,
            // 새로운 Css를 적용해주기 위한 customClass 설정
            customClass: {
                container: 'swal-container',
                popup: 'my-swal-popup'
            }
        }).then((result) => {
            // Swal이 닫힌 후 실행할 코드
            if (onClose) {
                onClose();
            }
        });
    }, [title, text, icon, onClose]);
    return null;
};

export default Child;
// toastAlert.scss
.swal-container {
  z-index: 1301 !important; // MUI Drawer 기본 z-index보다 높은 값
}

.my-swal-popup {
  z-index: 1301 !important; // 동일하게 높은 값 설정
}

 

그럼 정상적으로 가장 최상단에 보여지게 된다.