devlog_owen
라이브러리) 예쁜 모달창 SweetAlert2 본문
728x90
1. 설치
npm install sweetalert2
# 또는
yarn add sweetalert2
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
2. 기본 사용법
import Swal from "sweetalert2";
Swal.fire("Hello!", "이것은 SweetAlert2 알림입니다.", "success");
📌 Swal.fire()의 매개변수
- 첫 번째 인자: 제목(title)
- 두 번째 인자: 내용(text)
- 세 번째 인자: 아이콘(success | error | warning | info | question)
3. 다양한 SweetAlert2 예제
Swal.fire({
title: "정말 삭제하시겠습니까?",
text: "이 작업은 되돌릴 수 없습니다!",
icon: "warning",
showCancelButton: true, // 취소 버튼 표시
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "네, 삭제합니다!",
cancelButtonText: "아니요, 취소!",
}).then((result) => {
if (result.isConfirmed) {
Swal.fire("삭제 완료!", "선택한 항목이 삭제되었습니다.", "success");
}
});
✔ showCancelButton: true → 취소 버튼 표시
✔ confirmButtonText, cancelButtonText → 버튼 텍스트 설정
✔ .then((result) => { ... }) → 사용자가 확인 버튼을 눌렀을 때 실행될 코드
(2) 사용자 입력값을 받는 알림창
Swal.fire({
title: "이름을 입력하세요",
input: "text",
inputPlaceholder: "여기에 입력...",
showCancelButton: true,
confirmButtonText: "확인",
cancelButtonText: "취소",
}).then((result) => {
if (result.value) {
Swal.fire(`입력한 값: ${result.value}`);
}
});
✔ input: "text" → 사용자가 텍스트 입력 가능
✔ result.value → 입력한 값 가져오기
(4) 자동 닫히는 알림창
Swal.fire({
title: "자동으로 닫힘",
text: "이 메시지는 2초 후에 사라집니다.",
icon: "success",
timer: 2000, // 2초 후 자동 닫힘 (밀리초 단위)
showConfirmButton: false, // 확인 버튼 제거
});
리액트에서 사용하기
📌 (1) 버튼 클릭 시 SweetAlert 띄우기 (React)
import React from "react";
import Swal from "sweetalert2";
const AlertButton = () => {
const showAlert = () => {
Swal.fire({
title: "React에서 SweetAlert2 사용!",
text: "정상적으로 작동합니다!",
icon: "success",
confirmButtonText: "확인",
});
};
return <button onClick={showAlert} className="p-2 bg-blue-500 text-white">알림 표시</button>;
};
export default AlertButton;
리액트에서 사용자입력 받는 모달
import React, { useState } from "react";
import Swal from "sweetalert2";
const InputAlert = () => {
const [name, setName] = useState("");
const handleInput = async () => {
const { value } = await Swal.fire({
title: "이름을 입력하세요",
input: "text",
inputPlaceholder: "여기에 입력...",
showCancelButton: true,
});
if (value) {
setName(value);
Swal.fire(`입력한 이름: ${value}`);
}
};
return (
<div>
<button onClick={handleInput} className="p-2 bg-green-500 text-white">
이름 입력
</button>
{name && <p>입력된 이름: {name}</p>}
</div>
);
};
export default InputAlert;
728x90